Force exception on attribute write access only one object

Chris Rebert clp2 at rebertia.com
Thu Jan 8 04:59:55 EST 2009


On Thu, Jan 8, 2009 at 1:38 AM, Thomas Guettler <hv at tbz-pariv.de> wrote:
> Hi,
>
> for debugging I want to raise an exception if an attribute is
> changed on an object. Since it is only for debugging I don't want
> to change the integer attribute to a property.
>
> This should raise an exception:
>
> myobj.foo=1
>
> Background:
> Somewhere this value gets changed. But I don't now where.

Completely untested:

class Protector(object):
    def __init__(self, delegate, *forbidden):
        self.__delegate = delegate
        self.__forbidden = set(forbidden)
    def __getattr__(self, name):
        return getattr(self.__delegate, name)
    def __setattr__(self, name, value):
        if name in self.__forbidden:
            raise TypeError("attempt to assign to forbidden attribute
'%s'" % name)
        setattr(self.__delegate, name, value)

x = Foo()
x = Protector(x, "bar")
x.bar = 6 #should raise TypeError

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list