Tyler Fox
Tyler Fox

Reputation: 190

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

Upvotes: 0

Views: 439

Answers (2)

Krupip
Krupip

Reputation: 4882

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)

Upvotes: 1

Erez
Erez

Reputation: 1430

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.

Upvotes: 1

Related Questions