Variable scope and caller

Erik Lechak elechak at bigfoot.com
Sun Dec 15 23:43:05 EST 2002


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.

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()

Thanks,
Erik



More information about the Python-list mailing list