variable scope

Alex Martelli aleax at aleax.it
Thu Nov 21 13:31:14 EST 2002


bart wrote:

> Could I modify variable present inside an object's method from external
> module without override method of this class?

No.  It makes no difference whether a local variable is a local
variable of a method or a local variable of some other function:
you cannot modify that local variable from anywhere except the
very function or method it's local to.  That's what local MEANS.


> Another question is: can I override an object's method locate in modeule
> B from module A when this object is created from another functions
> presents inside module B?
> 
> Example:
> 
> Module A ---->  Module B ---> function A ---> function B ---> object A

That's a bit hard to follow -- you may want to post to it.comp.lang with 
[Python] at the start of your subject to put your question in Italian, or
visit www.python.it and join one or more of the mailing lists mentioned
there, again so you can explain your problem in Italian and I (or any of
the many other Italian Python enthusiasts) can answer similarly.

Anyway, what I think you're asking for can be done but it's tricky.
Say that B.py is as follows:

class Bclass:
  def say(self): print "ciao"
def Bfunc():
  return Bclass()


And you would like your A.py module to be able to do:

import B

class Aclass(B.Bclass):
  def say(self): print "salve"

# do something magical here

B.Bfunc().say()

and have it print "salve".  OK, then if that's what you want
you can do it -- in place of the "#do something magical here" put:

B.Bclass = Aclass

and there you are.  It IS tricky, because ALL later uses of
B.Bclass get affected, not JUST those in function B.Bfunc...
you can get THAT effect too, but it's even trickier and it
starts to edge into black magic...:

import new
fakeglobalsdict = B.__dict__
fakeglobalsdict['Bclass'] = Aclass
B.BFunc = new.function(B.BFunc.func_code, fakeglobalsdict)

that requires several caveats and I'm not going to post a
couple thousand lines about it -- perhaps it's better if you
explain (here or in the Italian NG/mailing lists) WHAT you
are trying to achieve with such trickery, there may be
simpler ways;-).


Alex




More information about the Python-list mailing list