Getting globals of the caller, not the defining module

Steven D'Aprano steve+comp.lang.python at
Mon Nov 11 12:25:42 CET 2013

Suppose I have a function that needs access to globals:

# module
def spam():
    g = globals()  # this gets globals from A

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

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?


More information about the Python-list mailing list