Variable scope and caller

Erik Lechak elechak at bigfoot.com
Sun Dec 15 16:47:48 EST 2002


Hello All,

Before I get to my question, I would just like to thank the people
that responded to my "perl to python" post.  I appreciated all the
info.  And I only had one person preach about the evils of perl.  The
way python handles documentation is awesome.  Reading non POD
documentation is a joy.

Here is my question.  In the following code, I want to be able to find
the value for 'y' in the function pstring.__str__.  Note that 'y'
exists in the scope of the calling function.

1)  How do I find the function that called me?
2)  How do I find out the local variables of a function when I am
deeper in the stack?
3)  How do I refer to the method testit (testit , main.testit,
__main__.testit ...)?


class pstring:
   data = ""

   def __init__(self, st = ""):
      self.data = st
      
   def __str__(self):
      print "-----------------------"
      print "GLOBALS"
      print globals()
      print "-----------------------"
      print "LOCALS"
      print locals()
      print "-----------------------"
      print "VARS"
      print vars()
      print "-----------------------"
      return self.data

def testit():
   y = "erik"
   x = pstring("hello $y")
   print x

testit()



Thanks,
Erik



More information about the Python-list mailing list