[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

possible to overide setattr in local scope?

glomde

1/22/2008 12:14:00 PM

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
2 Answers

Diez B. Roggisch

1/22/2008 12:18:00 PM

0

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

Terry Reedy

1/23/2008 3:41:00 AM

0


"glomde" <brkict@gmail.com> wrote in message
news:9dac9675-992e-4dc5-b085-06f0811939ca@1g2000hsl.googlegroups.com...
| 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

An assignment at module level amounts to setting an attribute of an
instance of the builtin (C coded) module type, which you cannot change.
Even if you can subclass that type (I don't know), there is no way to get
the (stock) interpreter to use instances of your module subclass instead.