Consider the following example:
class A():
def __init__(self):
self.veryImportantSession = 1
a = A()
a.veryImportantSession = None # ok
# 200 lines below
a.veryImportantSessssionnnn = 2 # I wanna exception here!! It is typo!
How could I make it so that an exception will be raised if I try to set a member that is not set in __init__?
Code above won’t fail when it is executed, but gives me a fun time to debug the problems.
Like with str:
>>> s = "lol"
>>> s.a = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'a'
Thanks!
You could override __setattr__ to only allow attribute names from a defined list.
In operation:
However, as msw has commented, attempts to make Python behave more like Java or C++ are usually a bad idea and will lead to losing lots of the benefits that Python provides. If you are concerned about making typos that might be missed then you are much better spending time writing unit tests for your code than trying to lock down the usage of your classes.