1

__slots__ declaration allows to restrict dynamic attributes declaration. But this is just one from a bunch of side effects of __slots__. How to restrict dynamic attributes declaration without __slots__?

Desired syntax:

class A(SomeSmrtClass):
    __allowed_attrs = set(['a', 'b'])

Desired behavior:

>>> a = A()
>>> a.a = 1 # Allowed
>>> a.c = 2 # Allowed in SomeSmartClass by deault
>>> a.d = 3
AttributeError: ...
I159
  • 29,741
  • 31
  • 97
  • 132
  • most common way is to override `__setattr__`. this is not an exact duplicate but related: http://stackoverflow.com/questions/20406363/setattr-versus-slots-for-constraining-attribute-creation-in-python?rq=1 – Corley Brigman Mar 04 '14 at 15:26
  • Do you have an actual concern about extra attributes being added to an instance of `A`, or is this just a question about whether it is possible? As long as the methods of `A` only attempt to use `a` and `b`, it doesn't really matter if an instance acquires extra attributes. – chepner Mar 04 '14 at 15:47
  • 1
    Attributes aren't declared in Python, they're created on-the-fly. Overriding `__setattr__` is hardly sufficient to prevent that -- in fact it may be impossible. Therefore IMHO pursuing this goal is likely a waste of time. – martineau Mar 04 '14 at 15:56
  • I've seen things designed to do this sort of thing using metaclasses, proxy class interfaces, and `__setattr__`/`__getattribute__`, but they generally end up being fragile and messy. You *can* do this, but you probably *shouldn't*. Also, `__slots__` exists more for efficiency than for allowing statically defined interfaces. What's your real problem here? Upstream users of your classes fat fingering things and getting runtime errors? – Silas Ray Mar 04 '14 at 16:19

0 Answers0