Python 有关函数中除locals()字典外的变量的信息

Python 有关函数中除locals()字典外的变量的信息,python,python-3.x,local-variables,Python,Python 3.x,Local Variables,正如预期的那样,此代码会引发UnboundLocalError x = 3 def f(): print("locals: " + str(locals())) if x==3: print("x is 3!") x = 1 f() 但是,正如我们从输出中看到的,locals()在开始时是一个空字典: locals: {} Traceback (most recent call last): File &q

正如预期的那样,此代码会引发UnboundLocalError

x = 3

def f():
    print("locals: " + str(locals()))
    if x==3:
        print("x is 3!")
    x = 1

f()
但是,正如我们从输出中看到的,locals()在开始时是一个空字典:

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
locals:{}
回溯(最近一次呼叫最后一次):
文件“C:/Users/user/PycharmProjects/try/scatch.py”,第10行,在
f()
文件“C:/Users/user/PycharmProjects/try/scatch.py”,第6行,在f中
如果x==3:
UnboundLocalError:赋值前引用了局部变量“x”
从我收集的资料来看,locals字典保存了Python所知道的关于函数中变量的所有信息。显然,情况并非如此:除了locals()之外,函数中还必须有一些关于变量的信息


我的问题是——这些信息到底是什么?我们可以在函数的开头访问其中的变量列表吗?

您在CPython中寻找的答案是
f.\uuuuuu code\uuuu.co\u varnames
模块中记录的


虽然
f.\uuuuu code\uuuu.co\u varnames
(如前所述)有效,但以下是查找本地分配的方法:

输出:

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 assignment
locals:{}
局部变量:{'x','y'}
回溯(最近一次呼叫最后一次):
文件“test.py”,第27行,在
f()
文件“test.py”,第21行,在f中
如果x==3:
UnboundLocalError:赋值前引用了局部变量“x”

显然,情况并非如此,您为什么这么说?在调用
locals()
的函数中,没有局部变量
x=1
直到函数的后面部分才会出现…
locals()
将为您提供在访问点绑定(分配)的局部变量。根据范围规则,在给定上下文中被视为局部变量的变量是不同的。然而,我不记得它们是从给定块内的任何点访问这些列表的iface。@JohnGordon-Python“知道”x变量将在以后重新定义。由于此信息不包含在locals()中,因此必须有另一个地方保存它。@OndrejK.-这就是我的意思:)也许我不够清楚
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 assignment