Looking up caller's namespace
scarblac-spamtrap at pino.selwerd.nl
Thu May 25 08:40:15 EDT 2000
Yves-Eric Martin wrote in comp.lang.python:
> 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).
Yes, this is possible. But not in a nice way.
You raise some exception (like 1/0), and catch it. Name you look at the
current exception as returned by sys.exc_info, and take the traceback
object. Go up its stack using some of its methods and maybe functions in the
traceback module, and find the function that called you, and its module.
However, this is black magic, implementation detail, meant for use in
debuggers only, and probably not the sort of thing you would want in Zope.
> 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...
I would try to set a default argument. I suppose you do
from somemodule import _
somewhere. Instead, I would try something like
_ = somemodule.gettext_factory(sys.modules['__name__'])
Where the gettext_factory is a function that returns a _ function with the
right default argument. I don't know if this is usable for you though.
Maybe watch out for circular references (in that case, don't pass the module
itself, just its name, let _ look it up in sys.modules itself).
Remco Gerlich, scarblac at pino.selwerd.nl
Signature server down. Manually insert witty comment here.
More information about the Python-list