2

如何访问非函数的全局变量?

目前我正在访问globals()然后手动硬编码我知道模块中存在的功能的删除,即

x, y, z = 1, 2, 3

def f(i, j):
    return i+j

def g():
   variables = globals()
   del variables['g']
   del variables['f']

这可以自动完成吗?(假设我不知道变量的类型,除了它们不应该是函数?

如果我要循环globals()并尝试在循环中删除它会很奇怪:

>>> import types
>>> x, y, z = 1,2,3
>>> def g():
...     variables = globals()
...     for k in variables:
...             if isinstance(variables[k], types.FunctionType):
...                     del variables[k]
... 
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in g
RuntimeError: dictionary changed size during iteration

我必须做类似的事情:

>>> def g():
...     variables = globals()
...     functions = []
...     for k in variables:
...             if isinstance(variables[k], types.FunctionType):
...                     functions.append(k)
...     for f in functions:
...             del variables[f]
... 
>>> g()

有没有更简单的方法来访问非函数的全局变量?


已编辑

>>> x, y, z = 1,2,3
>>> def f(i,j):
...     return i+j
... 
>>> globals()
{'f': <function f at 0x105f6df50>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': 1, 'y': 2, '__name__': '__main__', 'z': 3, '__doc__': None}
>>> def g():
...     print globals()
... 
>>> g()
{'g': <function g at 0x105f72320>, 'f': <function f at 0x105f6df50>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': 1, 'y': 2, '__name__': '__main__', 'z': 3, '__doc__': None}
4

0 回答 0