是否可以检测函数中声明的局部变量的数量?
Is it possible to detect the number of local variables declared in a function?
在 Python 测试夹具中,是否可以计算一个函数在其主体中声明了多少个局部变量?
def foo():
a = 1
b = 2
Test.assertEqual(countLocals(foo), 2)
或者,有没有办法查看函数是否声明了任何变量?
def foo():
a = 1
b = 2
def bar():
pass
Test.assertEqual(hasLocals(foo), True)
Test.assertEqual(hasLocals(bar), False)
我正在考虑的用例与验证用户提交的代码有关。
是的,关联代码对象占co_nlocals
属性中的所有本地名称:
foo.__code__.co_nlocals
演示:
>>> def foo():
... a = 1
... b = 2
...
>>> foo.__code__.co_nlocals
2
User-defined functions
[...]
__code__
The code object representing the compiled function body.
Code objects
[...]
Special read-only attributes: [...] co_nlocals
is the number of local variables used by the function (including arguments); [...]
为了详细说明@Martijn 的出色答案,如果您阅读 inspect — Inspect live objects 模块的文档,您会发现它允许自省大量数据,包括(如@Martijn 所指出的) code
类型,以下属性:
co_names tuple of names of local variables
co_nlocals number of local variables
在 Python 测试夹具中,是否可以计算一个函数在其主体中声明了多少个局部变量?
def foo():
a = 1
b = 2
Test.assertEqual(countLocals(foo), 2)
或者,有没有办法查看函数是否声明了任何变量?
def foo():
a = 1
b = 2
def bar():
pass
Test.assertEqual(hasLocals(foo), True)
Test.assertEqual(hasLocals(bar), False)
我正在考虑的用例与验证用户提交的代码有关。
是的,关联代码对象占co_nlocals
属性中的所有本地名称:
foo.__code__.co_nlocals
演示:
>>> def foo():
... a = 1
... b = 2
...
>>> foo.__code__.co_nlocals
2
User-defined functions
[...]
__code__
The code object representing the compiled function body.Code objects
[...]
Special read-only attributes: [...]
co_nlocals
is the number of local variables used by the function (including arguments); [...]
为了详细说明@Martijn 的出色答案,如果您阅读 inspect — Inspect live objects 模块的文档,您会发现它允许自省大量数据,包括(如@Martijn 所指出的) code
类型,以下属性:
co_names tuple of names of local variables
co_nlocals number of local variables