简体   繁体   中英

How can I implicitly pass the current global namespace in Python

I would like to implicitly pass a reference of the current global namespace to a function so that I can edit it. I feel like it could be possible because exec() does it, but that may be too special of a case.

spam.py

# This will fail because globals() grabs the spam.py globals
# I would like to to grab the globals from wherever it was called from

def writeOtherGlobals( implicitGlobals=globals() ):
    print "Got sausages", implicitGlobals['sausages']
    implicitGlobals['sausages'] = 10

eggs.py

from spam import writeOtherGlobals
sausages = 5
writeOtherGlobals()
print sausages # I want this to print 10
import inspect

def get_globals():
    return inspect.stack(1)[1][0].f_globals

This function will return a dictionary of the globals for the context from which it was called.

You can use the 'dir(module)` method, and exclude __ variables (to ignore name etc) or you might want to add a variable at the end of your module like so:

#in module.py
a = ...
b = ...
# function/class definitions etc...
_globals = globals()

so now you can do

# in anothermodule.py
import module
print module._globals

All your globals are now printed, and you can access each one as if you called globals() in the original class.

Note you don't need to know the name of module.py for this to work, as long as your module has a ._globals it doesn't matter what it is named, ie this works

def get_globals(module_py):
    print(module_py._globals)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM