Dan*_*Dan 21 python namespaces
是否可以编写一个将对象插入全局命名空间并将其绑定到变量的函数?例如:
>>> 'var' in dir()
False
>>> def insert_into_global_namespace():
... var = "an object"
... inject var
>>> insert_into_global_namespace()
>>> var
"an object"
Run Code Online (Sandbox Code Playgroud)
jol*_*lvi 33
它很简单
globals()['var'] = "an object"
Run Code Online (Sandbox Code Playgroud)
和/或
def insert_into_namespace(name, value, name_space=globals()):
name_space[name] = value
insert_into_namespace("var", "an object")
Run Code Online (Sandbox Code Playgroud)
备注这globals是一个内置关键字,即'globals' in __builtins__.__dict__评估为True.
Rol*_*ier 18
但请注意,分配声明为全局的函数变量只会注入模块命名空间.导入后,您无法全局使用这些变量:
from that_module import call_that_function
call_that_function()
print(use_var_declared_global)
Run Code Online (Sandbox Code Playgroud)
你明白了
NameError: global name 'use_var_declared_global' is not defined
Run Code Online (Sandbox Code Playgroud)
您必须再次导入以导入那些新的"模块全局变量".内置模块是"真正的全球",但:
class global_injector:
'''Inject into the *real global namespace*, i.e. "builtins" namespace or "__builtin__" for python2.
Assigning to variables declared global in a function, injects them only into the module's global namespace.
>>> Global= sys.modules['__builtin__'].__dict__
>>> #would need
>>> Global['aname'] = 'avalue'
>>> #With
>>> Global = global_injector()
>>> #one can do
>>> Global.bname = 'bvalue'
>>> #reading from it is simply
>>> bname
bvalue
'''
def __init__(self):
try:
self.__dict__['builtin'] = sys.modules['__builtin__'].__dict__
except KeyError:
self.__dict__['builtin'] = sys.modules['builtins'].__dict__
def __setattr__(self,name,value):
self.builtin[name] = value
Global = global_injector()
Run Code Online (Sandbox Code Playgroud)
Bre*_*arn 16
是的,只需使用该global声明即可.
def func():
global var
var = "stuff"
Run Code Online (Sandbox Code Playgroud)
Roland Puntaier 的答案更简洁的版本是:
import builtins
def insert_into_global_namespace():
builtins.var = 'an object'
Run Code Online (Sandbox Code Playgroud)