Looking up caller's namespace
andres at corrada.com
andres at corrada.com
Thu May 25 06:43:04 EDT 2000
On Thu, May 25, 2000 at 06:42:38PM +0900, Yves-Eric Martin wrote:
>
> I need your help for a problem my little Python knowledge cannot
> solve. In short, what I want to do is to access, from a function in a
> module, an object of the caller. The catch is that I don't want to pass
> it as an argument to the function, but to look it up in the caller's
> namespace. (See note 2 for why I want to do that).
>.
>.
>.
> Note 1: I am currently using the following workaround (which may actually
> be nicer than what I am trying to do, but it does not answer my
> question about accessing caller's namespace):
>
> --- mymodule.py ---
> def myadd(y,z):
> return y+z
> -------------------
>
> ----- test.py -----
> import mymodule
> def myadd(a):
> return mymodule.myadd(a,b)
> a,b=3,4
> print myadd(a)
> -------------------
>
I don't know the answer to your question but I came up with another
workaround:
class AllKnowing:
def __init__( self, callingNamespace ):
self.__dict__ = callingNamespace
def sum( self, a ):
z = self.__dict__['b']
return a + z
Firing up the interpreter I get:
>>> knowItAll = AllKnowing( globals() )
>>> b = 1
>>> knowItAll.sum( 2 )
3
------------------------------------------------------
Andres Corrada-Emmanuel Email: andres at corrada.com
------------------------------------------------------
More information about the Python-list
mailing list