Importing Variable Names Into Class Namespace
Is it possible to import global variables into an object's instance namespace? In a structure like this: ./mypackage/module1.py ./config.py ./script1.py If config.py has: #config
Solution 1:
This problem is a little confusing. There are three parts.
config
: contains variables you want.
script
: contains your logical code and variables imported from config
.
module
: contains functions' definition.
When you call MC.test
, it will find MYSETTING
in module
's namespace, but what you want is to find in script
's namespace. So in test
function, what you real want is to access parent frame's global namespace.
In this case, you need to use inspect
built-in module.
import inspect
print(inspect.current_frame().f_back.f_globals["MYSETTING"])
inspect.current_frame()
will return current frame, and f_back
refers to parent frame which is the frame calling this function, then f_globals
refers to frame's globals()
Post a Comment for "Importing Variable Names Into Class Namespace"