0

Consider the following code:

class Test:
    def __init__(self):
        self.historical = 5

t = Test()

# correct
print(t.historical)

# ops .. I made a mistake!
# an attribute error is thrown
#print(t.history)

# let's redefine the variable

# correct!
t.historical = 10

# ops ... I made a mistake!
t.history = 15 # <-- I want Python to throw an exception here

print(t.historical)
print(t.history)

In this code, I made a mistake: I assigned to history while the correct attribute name was historical.

How can I have Python throw an exception when I assign to history?

What is the best design decision to achieve this?

robertspierre
  • 3,218
  • 2
  • 31
  • 46
  • Implement `__setattr__` or use `__slots__`? – Timus Feb 25 '22 at 14:03
  • You can specify `__slots__ = 'historical',`, note that particular care must be taken if you intend on using inheritance. See https://stackoverflow.com/questions/472000/usage-of-slots – mwo Feb 25 '22 at 14:06
  • https://stackoverflow.com/questions/59376404/prevent-creating-new-attributes-for-class-or-module or https://stackoverflow.com/questions/3603502/prevent-creating-new-attributes-outside-init ? – ken Feb 25 '22 at 14:09

0 Answers0