Giter VIP home page Giter VIP logo

koxudaxi / pydantic-pycharm-plugin Goto Github PK

View Code? Open in Web Editor NEW
418.0 418.0 14.0 8.18 MB

PyCharm plugin for pydantic. This plugin provides autocompletion, inspection, type-checking, inserting unfilled argument, and more.

Home Page: https://koxudaxi.github.io/pydantic-pycharm-plugin/

License: MIT License

Kotlin 68.20% Python 31.73% HTML 0.07%
autocomplete fastapi inspection intellij intellij-plugin jetbrains kotlin pycharm pycharm-plugin pydantic

pydantic-pycharm-plugin's Introduction

Hi there πŸ‘‹,

I am a software developer who enjoys contributing to Open Source Software (OSS) with a goal to make the development environment friendlier πŸ˜„.

Here are some of the projects I've worked on:

If any of my tools have been helpful in your projects, would you consider sponsoring me? Your support would really make a difference and help me continue to maintain and improve these tools for everyone. Thank you! πŸš€

pydantic-pycharm-plugin's People

Contributors

actions-user avatar alek-sun avatar dependabot-preview[bot] avatar dependabot[bot] avatar dmontagu avatar github-actions[bot] avatar kotlinisland avatar koxudaxi avatar lada-gagina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pydantic-pycharm-plugin's Issues

Custom Fields not recognised by PyCharm

I have the following custom Field:

class NonEmptyString(str):
     @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if v == "":
            raise ValueError("Non-empty string expected")
        return v

and a model using it:

class MyModel(BaseModel):
    field: NonEmptyString

but when I instantiate MyModel:

my_model = MyModel(field="a string")

I get the following warning from pycharm's linter:

Expected type 'NonEmptyString' got 'str' instead

Is this behaviour expected?

Versions
pydantic 1.1.1
pycharm-pydantic-plugin: 0.0.27

Feature Request: Refactor from `__init__` signature updates model names.

Feature Request

In response to #16, it is now the case that refactors for class attributes result in a dialog offering the ability to change the variable names in __init__ calls. This is extremely useful, and it is now possible in theory to do safe __init__-call refactors by just modifying the attribute name on the class.

However, it would still be nice to be able to perform the refactor operation directly from inside the __init__ call, and have it update the class variable name and other __init__ call keyword arguments.

This is a substantially lower priority since you can accomplish this now by just jumping to the class definition first and refactoring there, but I wanted to create an issue for tracking.

Checking type with Enum, HttpUrl, conlist

I love your awesome plugin. However, there is some problem like below.

image

In the picture, number, url, urls are maybe wrong but con_urls is correct when instantiating a Bar. Hmm...Let's run the code

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    bar = Bar(
  File "/Users/spike/works/catalog/venv/lib/python3.8/site-packages/pydantic/main.py", line 283, in __init__
    raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Bar
con_urls
  ensure this value has at most 1 items (type=value_error.list.max_items; limit_value=1)

Truth is only con_urls is incorrect. pydantic said the opposite of what plugin says. In addition, the plugin doesn't check those item's type and quantity at all!

I have an opinion. First, the member of Foo, one is driven from str and Enum both.

>>> isinstance(Foo, str)
True
>>> Foo.one == 'one'
True

So it is really okay to assign directly but the plugin show warning message: Expected type 'Foo', got 'str' instead.

Some people may think Foo is not str but Foo itself and should code with Foo.one. Okay, maybe they are right. How about HttpUrl?

>>> url = HttpUrl(url='http://example.com', scheme='http', host='example.com')
>>> isinstance(url, str)
True
>>> url == 'http://example.com'
True

I got it! It's the answer! And I decided to ignore conlist! Problem solved!

image

If someone says I have to code like above to avoid the problem, I will never use pydantic. Remember, the problem belongs to the plugin, not pydantic. I just want to type url directly without HttpUrl. BTW, instantiating HttpUrl is sucks.

I hope the problem fixed soon.

Overridden fields not replaced

See screenshot. In general, overriding the type of an annotated field in a subclass doesn't affect it (though going from optional to non-optional is the only case of this that I use).

Not sure if this would be a hard fix or not, but figured I'd flag it. It looks like neither the dataclasses.dataclass or attr.dataclass decorator do this either, so maybe it's not possible in PyCharm anyway. (mypy does handle it as intended though...)

Screen Shot 2019-08-08 at 12 39 52 AM

Support field without a type hint

(Sorry for so many issues, just noting things when I find them)

In the following example:

from pydantic import BaseModel

class Foobar(BaseModel):
    x: int
    y = 10

Foobar(x=1, y=2)

pydantic knows that y is an int. (This will be discouraged in v1 because of inferring field order, but will definitely still be possible)

The plugin is currently ignoring y altogether:

image

Version 0.5.0 [add useful features]

Version 0.4 will support useful features.

TODO

  • freeze a list of features
  • implement features

Features

  • Jump to pydantic official document from code #141
  • Insert Field by Quick Fix enhancement #139

Bug: interaction with typing.cast

Plugin version: 0.0.8

from typing import cast, List

from pydantic import BaseModel

class Model(BaseModel):
    number: int

class SubModel(Model):
    pass

submodel = SubModel(number=1)
model = cast(Model, submodel)

models: List[Model] = [submodel, model]
known_submodel = cast(SubModel, models[-1])

I think the above should result in no errors. However:

Screen Shot 2019-08-09 at 1 02 45 PM

messes with cls(...) initialization

The plugin is currently displaying a false warning for the following valid code:

class Foo:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def bar(cls):
        return cls(1, 2)

Without the plugin:
image

With the plugin:
image

Running v0.0.18

Here's a more severe example from within pydantic's source code:

image

Bug: Field names treated with incorrect scope

If you create a local variable in a method with the same name as a field, you get strange behavior from PyCharm. In particular, it seems to consider the field a local variable inside the method.

Note the difference in behavior in the following two screenshots when the class is a subclass of BaseModel vs. not:

Screen Shot 2019-11-26 at 1 12 08 PM
Screen Shot 2019-11-26 at 1 09 58 PM

Wrong behaviour with allow_population_by_field_name

from typing import Dict, Any

from pydantic import BaseConfig, BaseModel, Extra, Field

BaseConfig.extra = Extra.forbid
BaseConfig.allow_population_by_field_name = True

class ItemChannelLinkDefinition(BaseModel):
    item_name: str = Field(alias='itemName')
    configuration: Dict[str, Any] = {}


ItemChannelLinkDefinition(item_name='asdf')

The Config switch allow_population_by_field_name means that it's allowed to use the field name in the constructor.
Unfortunately the plugin shows an error.

grafik

Bug: PyCharm-detected plugin error

Here's the traceback:

kotlin.TypeCastException: null cannot be cast to non-null type com.jetbrains.python.psi.impl.references.PyReferenceImpl
	at com.koxudaxi.pydantic.PydanticInspection$Visitor.visitPyCallExpression(PydanticInspection.kt:31)
	at com.jetbrains.python.psi.impl.PyCallExpressionImpl.acceptPyVisitor(PyCallExpressionImpl.java:28)
	at com.jetbrains.python.psi.impl.PyBaseElementImpl.accept(PyBaseElementImpl.java:72)
	at com.intellij.codeInspection.InspectionEngine.acceptElements(InspectionEngine.java:75)
	at com.intellij.codeInspection.InspectionEngine.createVisitorAndAcceptElements(InspectionEngine.java:63)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.runToolOnElements(LocalInspectionsPass.java:297)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$null$5(LocalInspectionsPass.java:265)
	at com.intellij.util.AstLoadingFilter.forceAllowTreeLoading(AstLoadingFilter.java:156)
	at com.intellij.util.AstLoadingFilter.forceAllowTreeLoading(AstLoadingFilter.java:148)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$null$6(LocalInspectionsPass.java:262)
	at com.intellij.util.AstLoadingFilter.disallowTreeLoading(AstLoadingFilter.java:127)
	at com.intellij.util.AstLoadingFilter.disallowTreeLoading(AstLoadingFilter.java:116)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$visitPriorityElementsAndInit$7(LocalInspectionsPass.java:262)
	at com.intellij.concurrency.ApplierCompleter.execAndForkSubTasks(ApplierCompleter.java:133)
	at com.intellij.concurrency.ApplierCompleter.tryToExecAllList(ApplierCompleter.java:231)
	at com.intellij.concurrency.ApplierCompleter.execAndForkSubTasks(ApplierCompleter.java:159)
	at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1101)
	at com.intellij.concurrency.ApplierCompleter.lambda$wrapInReadActionAndIndicator$1(ApplierCompleter.java:105)
	at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:591)
	at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:537)
	at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:59)
	at com.intellij.concurrency.ApplierCompleter.wrapInReadActionAndIndicator(ApplierCompleter.java:116)
	at com.intellij.concurrency.ApplierCompleter.lambda$compute$0(ApplierCompleter.java:96)
	at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:164)
	at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:204)
	at com.intellij.concurrency.ApplierCompleter.compute(ApplierCompleter.java:96)
	at java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:731)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
	at java.util.concurrent.ForkJoinPool$WorkQueue.pollAndExecCC(ForkJoinPool.java:1190)
	at java.util.concurrent.ForkJoinPool.helpComplete(ForkJoinPool.java:1879)
	at java.util.concurrent.ForkJoinPool.awaitJoin(ForkJoinPool.java:2045)
	at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1036)
	at com.intellij.concurrency.JobLauncherImpl.invokeConcurrentlyUnderProgress(JobLauncherImpl.java:58)
	at com.intellij.concurrency.JobLauncher.invokeConcurrentlyUnderProgress(JobLauncher.java:58)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.visitPriorityElementsAndInit(LocalInspectionsPass.java:268)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.inspect(LocalInspectionsPass.java:200)
	at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.collectInformationWithProgress(LocalInspectionsPass.java:119)
	at com.intellij.codeInsight.daemon.impl.ProgressableTextEditorHighlightingPass.doCollectInformation(ProgressableTextEditorHighlightingPass.java:84)
	at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:55)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$null$1(PassExecutorService.java:429)
	at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1106)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$2(PassExecutorService.java:422)
	at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:591)
	at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:537)
	at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:59)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:421)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$run$0(PassExecutorService.java:397)
	at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:164)
	at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:204)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:395)
	at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:161)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

It isn't causing any issues with usability, but I figured sharing the traceback couldn't hurt.

Prompt to install with using pydantic

I think pycharm sometimes prompts me to install packages based on what I'm using.

Is it possible to get pycharm to prompt users to install this plugin whenever they import or install pydantic?

stub deletion error

Describe the bug
There is this error in logs

java.io.IOException: Cannot delete '/home/koudai/.cache/JetBrains/PyCharm2020.2/python_stubs/-1247971761/pydantic'
	at com.intellij.openapi.vfs.impl.local.LocalFileSystemBase.deleteFile(LocalFileSystemBase.java:352)
	at com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl.deleteFile(PersistentFSImpl.java:508)
	at com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry.delete(VirtualFileSystemEntry.java:206)
	at com.koxudaxi.pydantic.PydanticPackageManagerListener$packagesRefreshed$1$$special$$inlined$runWriteAction$1.compute(actions.kt:79)
	at com.intellij.openapi.application.impl.ApplicationImpl.lambda$runWriteAction$16(ApplicationImpl.java:989)
	at com.intellij.openapi.application.impl.ApplicationImpl.runWriteActionWithClass(ApplicationImpl.java:968)
	at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:989)
	at com.koxudaxi.pydantic.PydanticPackageManagerListener$packagesRefreshed$1.run(PydanticPackageManagerListener.kt:22)
	at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:201)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:802)
	at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeLater$4(ApplicationImpl.java:322)
	at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:84)
	at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:132)
	at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47)
	at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:188)
	at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
	at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:776)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
	at java.base/java.security.AccessController.doPrivileged(Native Method)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
	at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:746)
	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:967)
	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:839)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:450)
	at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:744)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:449)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:802)
	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:497)
	at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

To Reproduce
I don't know when the error happened

Expected behavior
No error

Environments (please complete the following information):

  • IDE: PyCharm Professional 2020.2
  • OS: Ubuntu 18.04.4 LTS
  • Pydantic Version 1.6.1
  • Plugin version 0.1.10

Support `alias` in Schema

Pydantic provides alias to support another field name.

I think this plugin should support the feature.

ss2019-09-08 1 13 09

Instructions to build from source

It looks like the intended way of installing this is to just directly "install from disk" the jar file you've included in the repo.

Is there any way you could include instructions for how to build the jar from source? I think this would alleviate some potential security concerns with installing the downloaded jar, since it is difficult to confirm it precisely reflects what is in the source.

I think if you add that, I think we might be able to convince samuelcolvin to add a link to this in the pydantic docs as the "unofficial pycharm plugin".

Support field type on Schema `default` argument.

Detail

The feature supports field type on Schema default argument when the field does not have annotation.

eg

from pydantic import BaseModel, Schema

class A(BaseModel):
   a = Schema(123)

A(a=456)  # correct. the type is int
A(a='abc') # wrong

PR

#47

Release roadmap

Release schedule

Version release issue detail code status target date
0.1.0 support dataclass released 2020/04/10
0.2.0 support Annotated released 2021/03
0.3.0 Support PyCharm2021.1 developing 2021/04/xx
0.4.0 add useful features developing 2021/xx/xx

Warning when using asdict on pydantic dataclasses

Hello, and thanks for the plugin

When using the regular dataclass method asdict on a pydantic dataclass, I get the following warning on Pycharm :

'dataclasses.asdict' method should be called on dataclass instances

Since pydantic dataclasses are a drop in replacement for dataclasses, it works fine when it is run, so I think the warning should be removed if possible (I'm unfamiliar with Pycharm plugins)

I'm using PyCharm pro 2019.2, with the pydantic plugin in version 0.0.14

To reproduce the issue, open a python file in Pycharm and type:

from pydantic.dataclasses import dataclass
from dataclasses import asdict

@dataclass
class Test:
    i: int
    
test_dataclass = Test(0)
asdict(test_dataclass)

You will see the warning above on test_dataclass

Add type and default value to popup of auto-completion

I want to look a type and a default value on popup of auto-completion

If some don't like the idea then, Would you please tell me?

Motivation

PyCharm show Model's class name on popup of auto-completion

However, I don't feel good that a popup of auto-completion doesn't show type and default value.

By the way, IntelliJ shows a type as default in Java/Kotlin

ScreenShot

I upload the screenshot of an experimental version.
I must handle a few definition cases.
ss2019-08-29 0 38 23

Define a master list of type equivalencies

Some values should be treated equivalently.
The list will be used for type-checking on the plugin and mypy.

  1. How do we generate the list?
  2. How do we use the list on the plugin and mypy?

Related Issues

#36
pydantic/pydantic#1055

Funding

  • You can sponsor this specific effort via a Polar.sh pledge below
  • We receive the pledge once the issue is completed & verified
Fund with Polar

Proper description keyword parsing

Hi! Thank you for your great plugin! I've noticed that when you have description keyword filled in BaseModel pydantic class then autocompletion shows me that parameter in hints. See screenshot
image

Jump to pydantic official document from code

We often read the official document when writing code.

  1. Open browser
  2. search pydnatic document.
  3. search some words in the searching area.
  4. check the document.

I want to jump to the document page from code.

InitVar support for dataclasses

Hi! Thanks for your plugin, it is really very useful when using pydantic.

I use dataclasses from pydantic, and in some of my classes I use fields declared using InitVar typing to mark them as init-only for later use in __post_init__. This plugin currently understands that the field should only be used for initialization.
and when I try to use it as an attribute of an object, it says about an error, but it doesn’t understand that instead of InitVar[int], you can use int and there should be no error.

Hope this is not very difficult to fix. Thanks!
image

Java version mismatch

Describe the bug
When I enable this plugin, it immediately fails, stating that it was compiled with Java version 55.0 and I have Java version 52.0.

Stack Trace

com.intellij.diagnostic.PluginException: While loading class com.koxudaxi.pydantic.PydanticTypedValidatorMethodHandler: com/koxudaxi/pydantic/PydanticTypedValidatorMethodHandler has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0 [Plugin: com.koxudaxi.pydantic]
	at com.intellij.ide.plugins.cl.PluginClassLoader.loadClassInsideSelf(PluginClassLoader.java:261)
	at com.intellij.ide.plugins.cl.PluginClassLoader.tryLoadingClass(PluginClassLoader.java:204)
	at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:93)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:348)
	at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getImplementationClass(ExtensionComponentAdapter.java:74)
	at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.createInstance(ExtensionComponentAdapter.java:36)
	at com.intellij.openapi.extensions.impl.XmlExtensionAdapter.createInstance(XmlExtensionAdapter.java:69)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapter(ExtensionPointImpl.java:480)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapters(ExtensionPointImpl.java:421)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.calcExtensionList(ExtensionPointImpl.java:248)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.getExtensionList(ExtensionPointImpl.java:242)
	at com.intellij.openapi.extensions.ExtensionPointName.getExtensionList(ExtensionPointName.java:42)
	at com.intellij.openapi.actionSystem.impl.ActionPreloader.preload(ActionPreloader.java:16)
	at com.intellij.openapi.application.Preloader.lambda$preload$0(Preloader.java:84)
	at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:170)
	at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:629)
	at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:581)
	at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:60)
	at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
	at com.intellij.openapi.application.Preloader.lambda$preload$1(Preloader.java:74)
	at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:215)
	at com.intellij.util.concurrency.BoundedTaskExecutor.access$200(BoundedTaskExecutor.java:26)
	at com.intellij.util.concurrency.BoundedTaskExecutor$1.execute(BoundedTaskExecutor.java:194)
	at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:207)
	at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:183)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:652)
	at java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:649)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:649)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedClassVersionError: com/koxudaxi/pydantic/PydanticTypedValidatorMethodHandler has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
	at com.intellij.util.lang.UrlClassLoader._defineClass(UrlClassLoader.java:423)
	at com.intellij.util.lang.UrlClassLoader.defineClass(UrlClassLoader.java:408)
	at com.intellij.util.lang.UrlClassLoader._findClass(UrlClassLoader.java:369)
	at com.intellij.ide.plugins.cl.PluginClassLoader.loadClassInsideSelf(PluginClassLoader.java:258)
	... 33 more

Environments (please complete the following information):

  • IDE: PyCharm Professional 2020.2 and 2020.1
  • OS: Windows 10
  • Plugin version: 0.1.10

Additional context
I believe PyCharm is configured to use the bundled version of Java provided by JetBrains

Feature Request: Auto-completion for Config fields

It would be great if we could see auto-completion choices for the model Config -- I always have to Cmd+Click through multiple layers of definitions to get to the declaration of BaseConfig before I can confirm the name of a Config attribute.

I have no idea how hard this would be since Config isn't declared to inherit from anything. But it would be awesome if it weren't too much work!

Support default values

Now default values are treated same as other attrs and default value won't show in a hint.

image
image

Is there a way to implement it?

Support positional arguments for dataclasses

It looks like arguments to pydantic dataclasses are treated as keyword-only, but actually the arguments to dataclasses are always positional (whether it is a pydantic dataclass or a built-in dataclass).

Screen Shot 2019-11-24 at 11 41 47 AM

I generally prefer to drop the keywords when using dataclasses since it results in shorter calls, and I can be confident the ordering is right since the creation is happening in my own code.

Ignore fields with leading "_"

import xmltodict, typing
from pydantic import BaseModel

Model = typing.TypeVar('Model', bound='HIPEventBase')

class HIPEventBase(BaseModel):
    __ROOT_TAG__ = "FOO"

    @classmethod
    def get_root_tag(cls) -> str:
        return cls.__ROOT_TAG__

    def xml(self) -> str:
        return xmltodict.unparse({self.__class__.get_root_tag(): self.dict(by_alias=True)})

    @classmethod
    def parse_xml(cls: typing.Type[Model], b: str) -> Model:
        # noinspection PyArgumentList
        return cls(**xmltodict.parse(b)[cls.get_root_tag()])

    x: int
    y: int

Please don't show __ROOT_TAG__ as a field that needs to be populated in constructor.

I think it would also be expected that any field starting with '_' is ignored (perhaps check into implementation details in pydantic source). I have verified that a leading __ prevents pydantic from creating a "field".

Parameter hint for dataclasses includes non-init fields

When using field(init=False) to indicate that a field is not to be included in the __init__ of a dataclasses, the parameter hint after installing the plugin includes these in the popup hint.

image

(I am also not sure if the double hint is expected, if not, I can open a separate issue)

Thanks for the amazing work!

reflect pydantic's type leniency

pydantic has lots of support for coercing types, however pydantic-pycharm-plugin current gives a message saying simply Expected type "x", got "y" instead:

image

Is there any possibility to change the error message to something like Field is of type "x", "y" may not be parsable to "x"? (or something cleaner, can't think right now)

Perhaps it might even be possible to not show a warning in some obvious cases eg, int or str when the field is of type datetime? If that's not possible, just making the message more friendly/correct might be simplest.

I can imagine that actually trying to parse the value and see if it'll work (eg. '1' will work for int but 'x' would not) would involve duplicating the whole of pydantic's logic in kotlin which is completely impossible. So I'm definitely not asking for that!

Feature request: Refactoring to rename a model attribute changes the name in initializers

This would bring it in-line with how doing a refactor on the __init__ signature works for normal classes. I could imagine this being hard to accomplish, in which case it may not be worth it, but it would be a very nice capability to have.

Neither the attrs nor dataclass plugins support this now, so it's by no means a need-to-have, but that didn't stop you from solving #4 ! And again, I think it would be very useful!


More concretely, right now, when you do a refactor, you go from this:

Screen Shot 2019-08-09 at 11 39 48 AM

to this:

Screen Shot 2019-08-09 at 11 39 54 AM

I would like it to instead go to this:

Screen Shot 2019-08-09 at 11 43 08 AM

False positive -- class 'Foo' accepts only keyword arguments

from typing import NamedTuple, Union, cast
from pydantic import BaseModel

class Foo(BaseModel):
    name: str

class Bar(BaseModel):
    index: int

FooBar = Union[Foo, Bar]
PendingEntry = NamedTuple('PendingEntry', [('payload', FooBar), ('expiry', float)])

request = cast(Bar, None)
# noinspection Pydantic
pending_entry = PendingEntry(request, 12.0)  # Pydantic plugin error: class 'Foo' accepts only keyword arguments

Feature request: Treat `validator` as producing a classmethod

If this is hard to fix, it's not a big deal, but it would be nice to reduce some of the warnings-clutter pycharm generates:

from pydantic import BaseModel, validator


class Model(BaseModel):
    x: int

    @validator("x")
    def double_x(cls, v):
        return v * 2

Screen Shot 2019-08-16 at 11 02 58 AM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.