Variable scope and caller
Gerhard Häring
gerhard.haering at gmx.de
Sun Dec 15 17:07:26 EST 2002
* Erik Lechak <elechak at bigfoot.com> [2002-12-15 13:47 -0800]:
> [...] 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?
This gets asked from time to time. You *can* do it if you
envfr na rkprcgvba, gura hfr gur genpronpx zbqhyr [1]
but, as we often ask on #python, *what are you really trying to do*?
> 2) How do I find out the local variables of a function when I am
> deeper in the stack?
As a Python programmer, you don't :-P
> 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):
> [...]
>
> def testit():
> y = "erik"
> x = pstring("hello $y")
> print x
>
> testit()
testit is a module-level function, so you refer to it with the name
'testit' as long as you're in the same module (no matter where there,
even deeply in a class, ...).
Gerhard
[1] If your MUA doesn't support rot13 decryption, you can enter this
into a Python prompt:
>>> u'envfr na rkprcgvba, gura hfr gur genpronpx zbqhyr'.encode('rot13')
;-)
--
Favourite database: http://www.postgresql.org/
Favourite programming language: http://www.python.org/
Combine the two: http://pypgsql.sf.net/
More information about the Python-list
mailing list