I have a class with a property with a custom setter to perform validation. I would like to be able to pass the property as a constructor parameter too, and call the setter from the constructor to reuse the validation logic:
class Part(object):
def __init__(self, pn):
# self._pn = None
self.pn = pn
@property
def pn(self):
return self._pn
@pn.setter
def pn(self, value):
if type(value) != str:
raise Exception("Part number must be a string")
self._pn = value # warning here
On the last line, PyCharm gives this warning:
Instance attribute _pn defined outside __init__
If I uncomment the self._pn = None
in the constructor then the warning goes away,
but I don't like it, because it's pointless code: if an exception is raised,
an object won't be created anyway, so what's the point setting an initial value?
Is this is a shortcoming of PyCharm / tooling, or am I doing it wrong? Is there a better way to achieve the same, without warnings, without pointless code, in a DRY way?