I have declared a class as follows:
class Runattr:
pass
run = Runattr()
run.cfg = 'some str'
When I am trying to access run.cfg further in my code, PyCharm gives me the following warning and I am not able to autocomplete run.cfg:
Unresolved attribute reference 'cfg' for class 'Runattr' Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.
I am new to using classes. Can someone tell me why I am seeing this warning and can this be modified to get rid of the warning?
It's just a PyCharm warning (not an error!), since it can't figure out whether that class really should have a cfg
attribute.
Assuming you're using a modern Python version, add an annotation for such a field:
class Runattr:
cfg: str # denotes there would/could be a string `cfg`
run = Runattr()
run.cfg = 'some str'
Classes and instances can nevertheless have any attributes (and heck, you can even do setattr(run, "oh this is fun", True)
to have an attribute that's not a valid Python identifier), it's just that IDEs can't be infinitely smart about the dynamic nature here.