Getting globals of the caller, not the defining module

Rotwang sg552 at hotmail.co.uk
Tue Nov 12 03:29:56 EST 2013


On 12/11/2013 01:57, Terry Reedy wrote:
> On 11/11/2013 7:02 AM, sg552 at hotmail.co.uk wrote:
>> (Sorry for posting through GG, I'm at work.)
>>
>> On Monday, November 11, 2013 11:25:42 AM UTC, Steven D'Aprano wrote:
>>> Suppose I have a function that needs access to globals:
>>>
>>> # module A.py
>>> def spam():
>>>      g = globals()  # this gets globals from A
>>>      introspect(g)
>>>
>>> As written, spam() only sees its own globals, i.e. those of the
>>> module in
>>> which spam is defined. But I want spam to see the globals of the caller.
>>>
>>> # module B
>>> import A
>>> A.spam()  # I want spam to see globals from B
>>>
>>> I can have the caller explicitly pass the globals itself:
>>>
>>> def spam(globs=None):
>>>      if globs is None:
>>>          globs = globals()
>>>      introspect(globs)
>>>
>>> But since spam is supposed to introspect as much information as
>>> possible,
>>> I don't really want to do that. What (if anything) are my other options?
>>
>> How about this?
>>
>> # module A.py
>> import inspect
>> def spam():
>>      return inspect.stack()[1][0].f_globals
>
> In Python 3, the attribute is __globals__.

Er... no it isn't? Sorry if I'm mistaken but I believe you're thinking 
of the attribute formerly known as func_globals. But in the above 
inspect.stack()[1][0] is not a function, it's a frame object. In fact 
it's the same thing as sys._getframe().f_back, I think.



More information about the Python-list mailing list