Is func_globals mutable?

后端 未结 1 437
故里飘歌
故里飘歌 2021-01-28 17:48

The Python documentation states:

__globals__ func_globals

A reference to the dictionary that holds the function’s gl

1条回答
  •  借酒劲吻你
    2021-01-28 18:43

    First, note that func.func_globals and func.__globals__ are two references to the same thing:

    Changed in version 2.6: The double-underscore attributes __closure__, __code__, __defaults__, and __globals__ were introduced as aliases for the corresponding func_* attributes for forwards compatibility with Python 3.

    In other words:

    >>> def foo(bar):
        pass
    
    >>> foo.__globals__ is foo.func_globals
    True
    

    When they are referred to as "read-only" attributes, this is because you cannot reassign the attribute:

    >>> foo.__globals__ = {}
    
    Traceback (most recent call last):
      File "", line 1, in 
        foo.__globals__ = {}
    TypeError: readonly attribute
    

    However, the object returned is mutable, as it's a dictionary. Therefore you can add keys to the dictionary and remove them from it (although I would recommend against removing any until you're sure you know what you're doing!):

    >>> foo.func_globals
    {'__builtins__': , 
     '__package__': None, 
     '__name__': '__main__', 
     'foo': , 
     '__doc__': None}
    >>> foo.func_globals['bar'] = 'baz'
    >>> del foo.func_globals['__doc__']
    >>> foo.func_globals
    {'bar': 'baz', 
     '__builtins__': , 
     '__package__': None, 
     '__name__': '__main__', 
     'foo': }
    

    0 讨论(0)
提交回复
热议问题