Roman Prokofyev

Chief Scientist at FAIRTIQ. I work on making public transport accessible for everyone.

Pycharm local variable type declaration

23 Jan 2013 » pycharm, en

Sometimes is it useful to make PyCharm know what type of variable you’re using inside the function. For example, it enables the auto-complete feature for the variable methods and quick navigation to the method source with Ctrl/Cmd + click.

While for the function arguments you can easily specify the type using the docstring notation like:

# (reStructured Text notation)
"""
:type arg1: list
:type arg2: dict
"""

the documentation about such feature for local variables is buried in the JetBrains forum threads and issue tracker (http://youtrack.jetbrains.com/issue/PY-4083). Here is the solution that worked for me:

var1 = a.object
""":type: MyModel"""

which means that var1 will be treated as MyModel type.