Python dynamic attribute creation

Stephen Hansen me+list/python at ixokai.io
Mon Jun 28 15:30:00 EDT 2010


On 6/28/10 12:09 PM, Alexander Kapps wrote:
> This seems to work quite well:
>
> class TypoProtection(object):
> def __init__(self):
> self.foo = 42
> self.bar = 24
>
> def _setattr(self, name, value):
> if name in self.__dict__:
> self.__dict__[name] = value
> else:
> raise AttributeError, "%s has no '%s' attribute" \
> % (self.__class__, name)
>
>
> self.__class__.__setattr__ = _setattr

This will only work the first time you make an instance: thereafter, 
__setattr__ will be on the class and future instances will refuse to 
allow the creation of "foo" and "bar", as they won't already exist in 
the new instance's dictionary.

That said, you can certainly make a class that only allows pre-approved 
attributes and prevents the creation of on the fly ones.

Something like (untested):

class TypoProtection(object):
     ALLOWED_ATTRIBUTES = ["foo", "bar"]
     def __setattr__(self, key, value):
         if key not in TypoProtection.ALLOWED_ATTRIBUTES:
             raise AttribuetError("TypoProtection does not have %s 
attribute." % (key,))

         return object.__setattr__(self, key, value)

Now, I would very rarely *do* such a thing, but you *could* if you 
wanted to. (You achieve a similar effect by abusing __slots__)


-- 

    ... Stephen Hansen
    ... Also: Ixokai
    ... Mail: me+list/python (AT) ixokai (DOT) io
    ... Blog: http://meh.ixokai.io/




More information about the Python-list mailing list