Skip to content Skip to sidebar Skip to footer

Can Pycharm Suggest Or Autocomplete Or Insert Type Hints?

Suppose I'd like to add type hints to my python2/3 code. What's the easiest way to do that in Pycharm? Aside from Pycharms own type inference, how can it help me write type hint?

Solution 1:

The underlying assumption is that you write your types yourself.

Types are meant to encode what you intend for your code to mean. While programs can often do a reasonable job at deducing human intent, at the end of the day, some human intervention is always going to be necessary.

(After all, what if a program deduces a set of types that happens to match your program, but ends up being completely wrong due to a bug in your code? Or what happens if you intended for your function to return an Iterable[str] but the program deduced List[str], or vice versa?)

That said, there are some programs such as pytype that attempt to automatically infer types for you. However, my understanding is that these types of programs are still under heavy development and can't handle all cases yet.

If you just want stubs, but don't care about having them be accurate/contain useful type annotations (perhaps you plan on editing the annotations later?), use "stubgen", which is a command line utility that's bundled by default when you install mypy.

But in the general case, I'd recommend adding type annotations by hand (perhaps starting with your most commonly-used files) and experiment with using auxiliary tools like stubgen or pytype where they make sense.

Solution 2:

Solution 3:

If you write docstrings for your methods and classes, PyCharm picks up on them! To clarify, PyCharm has default type inference, but docstrings are supplemental and optional - they add extra assistance from the IDE. It's also a very good habit to get into.

https://www.jetbrains.com/help/pycharm/2017.1/using-docstrings-to-specify-types.html

https://www.python.org/dev/peps/pep-0257/

Post a Comment for "Can Pycharm Suggest Or Autocomplete Or Insert Type Hints?"