如预期的那样,此代码将引发一个UnboundLocalError。
x = 3
def f():
print("locals: " + str(locals()))
if x==3:
print("x is 3!")
x = 1
f()但是,正如我们从输出中看到的,局部变量()在开头是一个空字典:
locals: {}
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/try/scatch.py", line 10, in <module>
f()
File "C:/Users/user/PycharmProjects/try/scatch.py", line 6, in f
if x==3:
UnboundLocalError: local variable 'x' referenced before assignment根据我收集的信息,本地字典保存了Python所知道的关于函数内变量的所有信息。显然,情况并非如此:除了局部变量()之外,还必须有一些关于函数内部变量的信息。
我的问题是-这些信息到底是什么?我们能在函数的开头访问它中变量的列表吗?
发布于 2021-01-07 23:46:01
您要在CPython中寻找的答案是在检查模块中记录的f.__code__.co_varnames。
>>> def f():
... print(f.__code__.co_varnames)
... x = 1
... y = 2
>>> f()
('x', 'y')发布于 2021-01-08 00:01:51
当f.__code__.co_varnames (如在orlp的回答中所指出的)工作时,下面是用天冬氨酸查找本地任务的方法
import inspect,ast
x = 3
def find_ass_in_func(func):
f_src = inspect.getsource(f)
f_ast = ast.parse(f_src)
return find_ass_in_src(f_ast.body)
def find_ass_in_src(bodies):
ass = set()
for b in bodies:
if isinstance(b, ast.Assign):
ass |= set(t.id for t in b.targets)
if(hasattr(b, "body")):
ass |= find_ass_in_src(b.body)
return ass
def f():
print("locals: " + str(locals()))
print("local variables:", find_ass_in_func(f))
if x==3:
print("x is 3!")
x = 5
y = 6 # just for demonstration purpose
x = 1
f()输出:
locals: {}
local variables: {'x', 'y'}
Traceback (most recent call last):
File "test.py", line 27, in <module>
f()
File "test.py", line 21, in f
if x==3:
UnboundLocalError: local variable 'x' referenced before assignmenthttps://stackoverflow.com/questions/65621315
复制相似问题