Access to the caller's globals, not your own
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Nov 16 03:13:19 EST 2016
On Monday 14 November 2016 16:55, eryk sun wrote:
> 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
Nice! That appears to work on Jython, but not IronPython.
Thanks for the suggestion.
--
Steven
299792.458 km/s — not just a good idea, it’s the law!
More information about the Python-list
mailing list