从函数中将变量插入全局命名空间?

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.

  • 这是迄今为止最好的答案.没有理由像其他答案那样做任何奇怪的魔法.我很伤心,我没有早点看到这个答案. (3认同)

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)

  • 如果在运行时之前不知道变量的名称怎么办? (3认同)
  • @martineau:`globals()['varname'] ='varvalue' (3认同)
  • @gsk:这个众所周知的技术只将名称插入到函数所在模块的名称空间中,这可能与调用者的名称不同. (2认同)

1''*_*1'' 7

Roland Puntaier 的答案更简洁的版本是:

import builtins

def insert_into_global_namespace():
    builtins.var = 'an object'
Run Code Online (Sandbox Code Playgroud)