alejandro
alejandro

Reputation: 1274

Attributes set with setattr show as unresolved references in PyCharm

I have a class that defines several attributes dynamically using setattr builtin. However, all uses of those attributes are shown as unresolved references by PyCharm. Is there a way (via code or PyCharm setting) to help PyCharm resolved those attributes?

Upvotes: 14

Views: 1667

Answers (2)

Giordano
Giordano

Reputation: 5570

Unfortunately you can not.

From my point of view, you can ignore the warning doing Alt + Enter on your dynamic attribute and then selecting "Ignore unresolved reference".

Or, if you don't want do it for all class attributes, you can add @DynamicAttrs in the class docstring.

Here an example:

class YourClassWithSeveralAttributes(object):
    """@DynamicAttrs""" # <-- here

    def __init__(self):
        setattr(self, 'foo', 1)
        setattr(self, 'bar', 2)
        setattr(self, 'foo1', 11)
        setattr(self, 'bar2', 22)

Keep in mind that none of previous solutions will make PyCharm able to recognize your dynamic attributes and the autocompletition feature will be not available for those attributes. They are just way to ignore the warnings.

Upvotes: 11

Sameh Ramadan
Sameh Ramadan

Reputation: 104

Try File --> Invalidate Caches / Restart --> Invalidate and Restart

Upvotes: -1

Related Questions