[Tutor] Accessing calling module's globals in a module
Roland Schlenker
rol9999@attglobal.net
Sat, 23 Jun 2001 09:59:18 -0500
Christopher Smith wrote:
>
> I would like to be able to print a list of variable names and id's in a
> function. From the documentation I have been able to determine that
> the code below is wrong for 2 reasons:
>
> >>> def idof2(*v):
> ... n=globals().keys()
> ... for vi in v:
> ... for ni in n:
> ... if id(ni)==id(vi): print ni,vi
> ...
> >>> idof2(a,b)
> >>>
>
> 1) when loaded from a module, globals() only accessess the globals of
> the module not the globals of the module that called the function.
>
> 2) the id of the global key (ni above) is not the same thing as the id of
> the object associated with the key. In writing this I caught the
> second error and replaced the definition with:
>
> >>> a=2
> >>> b=3
> >>> def id1(*v):
> ... n=globals()
> ... for vi in v:
> ... for nk in n.keys():
> ... if id(n.get(nk))==id(vi):
> ... print nk + "'s id = "+str(id(vi))
> ...
> >>> id1(a,b)
> a's id = 14986968
> b's id = 14986920
>
> HOWEVER, if I put this in a module and try to import it it no longer
> works b/c of problem (1). I've looked through the (very useful but no
> longer active(?) FAQ) and the documentation. Can anyone point me
> toward how to access the calling modules global variables?
>
> Thanks.
>
> /c
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
Simply pass your caller's globals to the function.
def id1(callerGlobals, *v):
for vi in v:
for k in callerGlobals.keys():
if id(callerGlobals.get(k)) == id(vi):
print k + "'s id = " + str(id(vi))
Use as:
id1(globals(), a, b)
I am curious, why do you need to know an objects memory location.
If you want to know if two objects are the same, use the keyword "is".
Python 2.0 (#0, Apr 14 2001, 21:24:22)
[GCC 2.95.3 20010219 (prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> a = [1]
>>> b = [1]
>>> a is b
0
>>> c = a
>>> c is a
1
>>> c is b
0
>>>
Roland Schlenker