possible to overide setattr in local scope?

G

glomde

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
 
D

Diez B. Roggisch

glomde said:
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
 
T

Terry Reedy

| 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top