Variable scope and caller
Ben Leslie
benno at sesgroup.net
Sun Dec 15 23:54:18 EST 2002
On Sun, 15 Dec 2002, Erik Lechak wrote:
> 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
>
>
> In other words the __str__ function will find the local variables (and
> globals) then do a replace on the elements of the string starting with
> '$'. This is one of the main features of perl and I would like to
> prove it to myself that python can handle it without resorting to all
> kinds of trickery.
Well, you need a little bit of trickery.
> In the bit of code below, what scope is 'a=locals()' in. I thought it
> would be in the calling functions scope. But it does not appear to
> be.
>
> I have also tried 'a=globals()' and 'a=vars()'.
>
> class pstring:
> data = ""
> def __init__(self, st = ""):
> self.data = st
> def __str__(self , a=locals()):
> print a
> return self.data
>
> def testit():
> y = "erik"
> x = pstring("hello $y")
> print x
>
> testit()
"""
import inspect
class pstring:
data = ""
def __init__(self, st = ""):
self.data = st
def __str__(self):
a = inspect.currentframe().f_back.f_locals
print a
print a['y']
return self.data
def testit():
y = "erik"
x = pstring("hello $y")
print locals()
print x
testit()
"""
Benno
More information about the Python-list
mailing list