user2923089
user2923089

Reputation: 39

How to protect class attributes in Python?

How to protect class from adding attributes in that way:

class foo(object):
     pass

x=foo()
x.someRandomAttr=3.14

Upvotes: 0

Views: 301

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121436

If you want an immutable object, use the collections.namedtuple() factory to create a class for you:

from collections import namedtuple

foo = namedtuple('foo', ('bar', 'baz'))

Demo:

>>> from collections import namedtuple
>>> foo = namedtuple('foo', ('bar', 'baz'))
>>> f = foo(42, 38)
>>> f.someattribute = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'foo' object has no attribute 'someattribute'
>>> f.bar
42

Note that the whole object is immutable; you cannot change f.bar after the fact either:

>>> f.bar = 43
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

Override the __setattr__ method:

>>> class Foo(object):
    def __setattr__(self, var, val):
        raise TypeError("You're not allowed to do this")
...     
>>> Foo().x = 1
Traceback (most recent call last):
  File "<ipython-input-31-be77d2b3299a>", line 1, in <module>
    Foo().x = 1
  File "<ipython-input-30-cb58a6713335>", line 3, in __setattr__
    raise TypeError("You're not allowed to do this")
TypeError: You're not allowed to do this

Even Foo's subclasses will raise the same error:

>>> class Bar(Foo):
    pass
... 
>>> Bar().x = 1
Traceback (most recent call last):
  File "<ipython-input-35-35cd058c173b>", line 1, in <module>
    Bar().x = 1
  File "<ipython-input-30-cb58a6713335>", line 3, in __setattr__
    raise TypeError("You're not allowed to do this")
TypeError: You're not allowed to do this

Upvotes: 3

Related Questions