Variable scope and caller
Dennis Lee Bieber
wlfraed at ix.netcom.com
Mon Dec 16 17:26:02 EST 2002
Ben Leslie fed this fish to the penguins on Sunday 15 December 2002
08:54 pm:
> a = inspect.currentframe().f_back.f_locals
Ah, the missing piece. And an optimization from the loops.
import inspect
class pstring:
def __init__(self, fstring):
self.format = fstring
def __str__(self):
inscope = {}
inscope.update(globals())
inscope.update(inspect.currentframe().f_back.f_locals)
return self.format % inscope
def aCaller():
y = "Dennis"
x = pstring("Who's %(y)s")
print x
y = "me"
print x
y = "erik"
z = "world"
x = pstring("Hello %(y)s")
g = pstring("Goodbye %(z)s")
print x
aCaller()
print x, g
y = "Wulfraed"
print x
print g
gives
Hello erik
Who's Dennis
Who's me
Hello erik Goodbye world
Hello Wulfraed
Goodbye world
Of course, I do see a flaw, the solution of which will be left as an
exercise for the student...
Namely, this only goes back ONE level of scope; I suspect one needs to
iterate on the frame stack to get to the bottom (top?) and then work
down to the current frame if one really wants to catch any version of
the named variable (rather than Python's Global and Local [one frame
up] system)
--
> ============================================================== <
> wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
> wulfraed at dm.net | Bestiaria Support Staff <
> ============================================================== <
> Bestiaria Home Page: http://www.beastie.dm.net/ <
> Home Page: http://www.dm.net/~wulfraed/ <
More information about the Python-list
mailing list