Variable scope and caller
Dennis Lee Bieber
wlfraed at ix.netcom.com
Mon Dec 16 17:18:47 EST 2002
Erik Lechak fed this fish to the penguins on Sunday 15 December 2002
08:43 pm:
> Hello all,
>
>
> This is what it would look like when it works:
>
> a = pstring("hello $b")
> b = "erik"
> print a
> b = "moon"
> print a
>
> OUTPUT
> hello erik
> hello moon
>
Are you willing to use Python formatting codes instead of PERL? That
makes it rather simpler -- at least you don't have to parse for the $.
I've not found a way to automatically get something from the "local"
scope of a calling function without explicitly passing the scope at
creation time, and that freezes the values within the caller. Works
fine for globals, however.
-=-=-=-=-=-=-=-
class pstring:
def __init__(self, fstring, callerscope=locals()):
self.format = fstring
self.scope = callerscope
def __str__(self):
inscope = {}
for (k,d) in globals().items():
inscope[k] = d
for (k,d) in self.scope.items():
inscope[k] = d
return self.format % inscope
def aCaller():
y = "Dennis"
x = pstring("Who's %(y)s",locals()) # freezes scope contents
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
-=-=-=-=-=-=-
>>>
Hello erik
Who's Dennis
Who's Dennis # effect of "frozen" scope, no local change caught
Hello erik Goodbye world
Hello Wulfraed
Goodbye world
I haven't tried invoking it from within another function.
--
> ============================================================== <
> 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