gpt4 book ai didi

python - 是否可以检测函数中声明的局部变量的数量?

转载 作者:行者123 更新时间:2023-11-28 20:03:45 25 4
gpt4 key购买 nike

在 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

参见 Datamodel documentation :

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); [...]

关于python - 是否可以检测函数中声明的局部变量的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com