Reputation: 31666
I often find myself having to start a debugging session in PyCharm only in order to inspect a variable and look up its class with something.__class__
so that I can insert the type hint into the code in order to make it more readable.
Is there a way to do it automatically in PyCharm via a context action, in VSCode or maybe some other tool?
Upvotes: 4
Views: 5598
Reputation: 55
For VSCode there are some extension for adding type hints:
I used IntelliSense.
Upvotes: 2
Reputation: 8411
Have you tried Adding type hints in the PyCharm?
The VSCode-Python has not supported this feature, and I have submitted a feature request on GitHub.
Upvotes: 2
Reputation: 12880
Is there a way to do it automatically in PyCharm via a context action
Well no! Because if you're getting a type hint of a subclass at run-time that does not mean you wouldn't want to (or should) insert the type hint of the superclass instead. (Or the type hint of an entirely different class if it's a Union, or even one of the unsupported features like an Intersection, etc... The possible combinations are countless and even tools like mypy can't check for them all statically, and much less dynamically...)
So there's no way to meaningfully automate the insertion of type hints because the IDE can't infer all the possible run time types, that's the job of programmer.
via a context action
The context actions are limited to Adding type hints but these still require you to fill in the fields by hand. You could try and use Inlay Hints but Python isn't part of the default inlay languages included in PyCharm (check the list at Settings
>
Editor
>
Inlay Hints
.) You could try a specific plugin to work for the Python inlay hints, for example Python Inlay Hints from JetBrains plugin marketplace, but I don't think it would do exactly what you want.
Lastly, there is an option called Collect run-time types information for code insight
see issue PY-38900 but in my personal experience this leads to inexplicable errors and often a stale cache causing more problems than it solves (reading posts on SO a few Django users find it useful but I also don't think it does what you want).
Upvotes: 5