Is there a way to explicitly tell PyCharm what class an attribute is an instance of?

StackOverflow https://stackoverflow.com/questions/9040387

  •  03-12-2019
  •  | 
  •  

Question

I recently picked up PyCharm and I'm used to a feature from Wing where you can tell the IDE what class a particular identifier (variable, attribute, whatever) will be. For example:

my_object = SomeClass()
assert isinstance(my_object.my_attribute, SomeOtherClass)

At this point, Wing knows exactly what my_object.my_attribute is even if it couldn't otherwise figure it out from source code analysis.

I'm looking for a similar feature in PyCharm. I know what a particular attribute of an object is, but PyCharm doesn't, so how can I tell it, so it can give me handy completions?

Related question: I also do see a similar question, How can I tell PyCharm what type a parameter is expected to be?, but it doesn't cover attributes, just parameters.

Était-ce utile?

La solution

Actually PyCharm also understands the 'assert isinstance' syntax, but only for unqualified references. I've filed an issue to support this for qualified references as well:

http://youtrack.jetbrains.net/issue/PY-5614

In the current version, you can specify the type of my_attribute by going to the declaration of SomeClass and adding a epydoc or sphinx docstring for the attribute.

Autres conseils

If I understand your question correctly what you are looking for is general type inference from PyCharm. Coming from a statically typed language, I was baffled when I used code completion and the the choices were about as numerous as the contents of the python library.

I have FOUND that in PyCharm it has the option to gather type information during runtime and make this available during development time (i.e. code completion).

Here is how you do...

Preferences > Python Debugger > "Collect run-time types for code insight"

As you "debug" you code (not you don't have to use breakpoint). PyCharm will begin provide better suggestions for all code navigation/completion.

Cheers

Picture of Debug Preferences

This is working for me (2.6.2)

class Rule (object):
    def __init__(self, *args):
        self.criteria = []
        """@type : list of Criterion"""
        crit = self.criteria[0]
        #on this line, code completion works for "crit"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top