【问题标题】:Is it possible to detect the number of local variables declared in a function?是否可以检测函数中声明的局部变量的数量?
【发布时间】:2016-09-17 16:23:26
【问题描述】:

在 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)

我正在考虑的用例与验证用户提交的代码有关。

【问题讨论】:

    标签: python metaprogramming


    【解决方案1】:

    是的,关联的代码对象占co_nlocals属性中的所有本地名称:

    foo.__code__.co_nlocals
    

    演示:

    >>> def foo():
    ...     a = 1
    ...     b = 2
    ...
    >>> foo.__code__.co_nlocals
    2
    

    见Datamodel documentation:

    用户自定义函数

    [...]

    __code__ 表示编译后的函数体的代码对象。

    代码对象

    [...]

    特殊只读属性:[...] co_nlocals 是函数使用的局部变量的数量(包括参数); [...]

    【讨论】:

      【解决方案2】:

      要详细说明@Martijn 出色的答案,如果您阅读inspect — Inspect live objects 模块的文档,您会看到它允许对大量数据进行内省,包括(如@Martijn 所述)code类型,以下属性:

      co_names    tuple of names of local variables
      co_nlocals  number of local variables
      

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 2020-10-27
        • 2022-01-11
        • 2023-03-24
        • 1970-01-01
        • 2020-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多