auto completion for dynamic module attributes in python

Answered

I was trying to dynamicly create attribute for instance. It works, but it will be better if the dynamic attribute can be auto-completed.

It is said that IDE uses dir() to get all attributes of a class. It works in python console, which mean when I type 'foo.', pycharm shows 'attr1' and 'attr2' in auto-completion. However it fails in the input area.

so my question is: how to realize auto completion for dynamic module attributes in pycharm

class Foo(object):
mapping = {
'attr1': 1,
'attr2': 2,
}

def __getattr__(self, item):
if item in self.mapping:
return self.mapping[item]

# change the result of dir(foo)
def __dir__(self):
return self.mapping.keys()


if __name__ == '__main__':
foo = Foo()
print foo.attr1 # want auto-completion for attr1/attr2 after 'foo.'
6 comments
Comment actions Permalink

Hi Czqing422! PyCharm can't provide completion for such a dynamic code but you can leverage PEP 484 type annotations and manually provide e.g. stub file with type annotations for class Foo:

You can also include field type annotation in class itself (example with Python 3.6 syntax):

but there's a pesky field names duplication in this case.

4
Comment actions Permalink

Thank you so much for answering my question! The stub file method solved my problem.

0
Comment actions Permalink

Stub files won't work for classes that have dynamic attributes though.

0
Comment actions Permalink

Hey,

Is that still the way it is described in the Pavel Karateev comment?

I.e. executing the following snippet results in different autocomplete behaviour (PyCharm 2019.1.2 on Windows 10 x64):

from transitions import Machine
class Model:
"""My dynamically extended Model

Attributes:
evaporate(callable): dynamically added method
"""
model = Model()
machine = Machine(model, states=['A', 'B'],
transitions=[['evaporate', 'A', 'B']], initial='A')

In the editor:


In Python Console:





0
Comment actions Permalink

Yes, Pavel's comment is still true in PyCharm 2019.3.3, however it's not related to the difference between editor's and console's code insight. 

Indeed, code insight works differently in the editor and in the console. In the latter case you request methods for an object that's already created in the memory. But the editor doesn't know about.

We have discussed how to improve the suggestions in such cases, but there's no plans for the near future.

2
Comment actions Permalink

Andrey, I understand the editor would not know dynamic attributes before execution but what about in code evaluation ? By the time one hits "Evaluating Expression" and attributes are created, code insight should read them from memory. It does not today (2020.3 EAP).

We use SimpleNamespace a lot and I had hope to see the attrs in the Evaluate window once the namespaces are created.

0

Please sign in to leave a comment.