Detect all global variables within a python function?

前端 未结 2 1822
栀梦
栀梦 2021-02-05 21:27

I am trying to analyze some messy code, that happens to use global variables quite heavily within functions (I am trying to refactor the code so that functions only use local va

2条回答
  •  温柔的废话
    2021-02-05 21:31

    As mentioned in the LOAD_GLOBAL documentation:

    LOAD_GLOBAL(namei)

    Loads the global named co_names[namei] onto the stack.

    This means you can inspect the code object for your function to find globals:

    >>> f.__code__.co_names
    ('y',)
    

    Note that this isn't sufficient for nested functions (nor is the dis.dis method in @kindall's answer). In that case, you will need to look at constants too:

    # Define a function containing a nested function
    >>> def foo():
    ...    def bar():
    ...        return some_global
    
    # It doesn't contain LOAD_GLOBAL, so .co_names is empty.
    >>> dis.dis(foo)
      2           0 LOAD_CONST               1 (", line 2>)
                  3 MAKE_FUNCTION            0
                  6 STORE_FAST               0 (bar)
                  9 LOAD_CONST               0 (None)
                 12 RETURN_VALUE
    
    # Instead, we need to walk the constants to find nested functions:
    # (if bar contain a nested function too, we'd need to recurse)
    >>> from types import CodeType
    >>> for constant in foo.__code__.co_consts:
    ...     if isinstance(constant, CodeType):
    ...         print constant.co_names
    ('some_global',)
    

提交回复
热议问题