Looking up caller's namespace

Yves-Eric Martin yemartin at garage.co.jp
Thu May 25 05:42:38 EDT 2000


    Hello Python gurus,


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


    A simple addition example. Usually, I would pass all arguments in
the call to the function as in the following:

--- mymodule.py ---
def myadd(y,z):
    return y+z
-------------------

----- test.py -----
>from mymodule import myadd
a,b=3,4
print myadd(a,b)
-------------------


    But what I want is something like:

--- mymodule.py ---
def myyadd(y):
    z=__caller's_namespace__['b']   # The spooky lookup...
    return y+z
-------------------

----- test.py -----
>from mymodule import myadd
a,b=3,4
print myadd(a)
-------------------


    I have looked through docs and list archive, but I could not find
the right way to do this "__caller's_namespace__['b']" lookup. Have I
used the wrong keywords or is there no straightforward way to do that?
Any hint on this would be greatly appreciated.


    Thanks.


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


Note 2: Why do I want to do this?

    I am working on an internationalization project for Zope, and we are
going for a gettext approach. The problem is that the language to which
to localize depends on a REQUEST object present in the current namespace.
And to minimize internationalization work, we want to replace a 'string'
by _('string'), not by _('string', REQUEST). Hence my problem...


-- 
Yves-Eric Martin
Digital Garage Inc.
yemartin at garage.co.jp




More information about the Python-list mailing list