possible to overide setattr in local scope?

Diez B. Roggisch deets at nospam.web.de
Tue Jan 22 13:18:05 CET 2008


glomde wrote:

> In a class it is poosible to override setattr, so that you can decide
> how you should
> handle setting of variables.
> 
> Is this possible to do outside of an class on module level.
> 
> mysetattr(obj, var, value):
>   print "Hello"
> 
> So that
> 
> test = 5
> 
> 
> would print
> Hello

No, that's not possible. What you could do instead is to create a singlton
that you use to store the values in, instead of the module directly. Like
this (untested):


class ModuleState(object):
   # borg pattern - why not...
   _shared_state = {}
   def __init__(self):
       self.__dict__ = ModuleState._shared_state

   def __setattr__(self, name, value):
       setattr(self, name, "hello")

state = ModuleState()

Then you do

state.test = 5

Diez



More information about the Python-list mailing list