Access to the caller's globals, not your own
eryk sun
eryksun at gmail.com
Mon Nov 14 00:55:49 EST 2016
On Mon, Nov 14, 2016 at 5:20 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> but what magic do I need? globals() is no good, because it returns the
> library's global namespace, not the caller's.
>
> Any solution ought to work for CPython, IronPython and Jython, at a minimum.
You can access the globals of the caller's frame, but you'll have to
research to what extent IronPython and Jython support CPython frame
objects.
FWIW:
import inspect
SPAMIFY = True
def make_spam(n):
caller_globals = inspect.currentframe().f_back.f_globals
if caller_globals.get('SPAMIFY', SPAMIFY):
return "spam" * n
else:
return "ham" * n
For example:
>>> import library
>>> library.make_spam(5)
'spamspamspamspamspam'
>>> SPAMIFY = False
>>> library.make_spam(5)
'hamhamhamhamham'
More information about the Python-list
mailing list