32

是否可以编写一个将对象插入全局命名空间并将其绑定到变量的函数?例如:

>>> 'var' in dir()
False
>>> def insert_into_global_namespace():
...        var = "an object"
...        inject var
>>> insert_into_global_namespace()
>>> var
"an object"
4

6 回答 6

45

这很简单

globals()['var'] = "an object"

和/或

def insert_into_namespace(name, value, name_space=globals()):
    name_space[name] = value

insert_into_namespace("var", "an object")

globals内置关键字的备注,即'globals' in __builtins__.__dict__计算结果为True

于 2014-12-24T21:47:51.947 回答
21

但请注意,分配声明为全局的函数变量只会注入模块命名空间。导入后不能全局使用这些变量:

from that_module import call_that_function
call_that_function()
print(use_var_declared_global)

你得到

NameError: global name 'use_var_declared_global' is not defined

您必须再次导入才能导入那些新的“模块全局变量”。内置模块虽然是“真正的全局”:

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()
于 2013-01-12T21:15:48.420 回答
19

是的,只需使用该global语句。

def func():
    global var
    var = "stuff"
于 2012-08-05T01:32:31.567 回答
3

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

import builtins

def insert_into_global_namespace():
    builtins.var = 'an object'
于 2016-10-08T20:24:44.700 回答
0

我认为没有人解释过如何创建和设置名称本身就是变量值的全局变量。

这是我不喜欢的答案,但至少它有效[1],通常是[2]。

我希望有人能告诉我一个更好的方法来做到这一点。我发现了几个用例,实际上我正在使用这个丑陋的答案:

########################################
def insert_into_global_namespace(
    new_global_name,
    new_global_value = None,
):
    executable_string = """
global %s
%s = %r
""" % (
        new_global_name,
        new_global_name, new_global_value,
    )
    exec executable_string  ## suboptimal!

if __name__ == '__main__':
    ## create global variable foo with value 'bar':
    insert_into_global_namespace(
        'foo',
        'bar',
    )
    print globals()[ 'foo']
########################################
  1. 出于多种原因,应避免使用 Python exec。

  2. 注意:请注意“exec”行(“unqualified exec”)上缺少“in”关键字。

于 2014-08-25T17:25:20.903 回答
-1
var = ""

def insert_global():    
    global var
    var = "saher"

insert_global()
print var
于 2014-12-24T22:12:43.140 回答