如何访问非功能性的全局变量?
目前我正在访问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}