Scan generated fields of the PyCharm class class

As a minimum case, I have an Example class that works like in abstract capacity for a number of other classes.

 class Example(object): def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) class Test(Example): def __init__(self, foo='bar'): super(Test, self).__init__(foo=foo) 

In the real case, Example does more.

Is there a way for Test to tell PyCharm that Test will have one Test.foo field and even better, tell it that foo is expected to be a string?

To be clear, consider delegating field settings from Example to Test .

The closest I got is @ivar Epydoc, but I can't get it to work

+5
source share
2 answers

As already mentioned, you cannot. However, you can tell PyCharm to accept the missing attributes using @DynamicAttrs :

 class Example(object): """ @DynamicAttrs """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) 

Update: If Python3.5 is an option, see this question on using tooltip types for dynamic attributes.

+5
source

I had exactly the same problem you encountered. I didn’t want to offer code, I just wanted PyCharm to stop warning me about undefined attributes ( foo is not attribute of class Test )

I could not fix the code hint problem, but I overcame this warning by implementing an Example class like this

 class Example(object): def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __getattr__(self, name): """ Does absolutely nothing, only for pycharm to stop complaining about massing attributes This function is *only* called when python fail to find certain attribute, so it always raises exception """ raise AttributeError("Attribute %s is not part of %s class" % (name, self.__class__.__name__)) 
+3
source

All Articles