4

Possible Duplicate:
How can I tell PyCharm what type a parameter is expected to be?

I've discovered that coding Python in IntelliJ IDEA (and PyCharm), you can use Epytext or reStructuredText to document expected types of parameters and return types. These can be provided as-needed to help the IDE in providing autocompletion and improve its inspections error checking.

What I can't quite figure out is how to specify type annotations for instance variables and class variables. Is there some way to do this in a way that IntelliJ will recognize?

For example, say IntelliJ cannot infer the return type of some_function(), and the function is in a library where we cannot add a @rtype comment. How can I provide the type for the self.bar instance variable?

class Foo:
    def __init__(self):
        # How can I document that self.bar is of type Bar?
        self.bar = some_function()

Edit:

Finally found the proper syntax for documenting the types of instance variables. Place a docstring directly after the variable assignment.

class Foo:
    def __init__(self):
        self.bar = some_function()
        """@type: Bar"""

Two things to note are that IntelliJ/PyCharm only seems to understand the variable docstring format. The comment docstring format, or specifying type in the class docstring does not work.

Also, there appears to be a bug where variable docstrings don't work for double-underscore prefixed variables.

Community
  • 1
  • 1
leedm777
  • 23,444
  • 10
  • 58
  • 87
  • The duplicate question states how to specify the type of a function parameter. I need to know how to specify the type of an instance variable. – leedm777 Jul 18 '12 at 05:50
  • According to http://youtrack.jetbrains.com/issue/PY-3142: PyCharm now supports specifying types for function parameters **and instance variables** using Epydoc or Sphinx comments (@type or :type). – CrazyCoder Jul 18 '12 at 07:50
  • After trial and error, I've discovered that it doesn't work if the instance variable has a double-underscore prefix, and also doesn't work for comment docstrings or class docstrings. That seems like enough of a difference to reopen this question. – leedm777 Jul 18 '12 at 14:46

0 Answers0