Home >Backend Development >Python Tutorial >Python built-in function locals

Python built-in function locals

高洛峰
高洛峰Original
2016-11-05 14:17:081290browse

English documentation:

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Explanation :

 1. The function returns a dictionary consisting of local variables in the current scope and their values, similar to the globals function (returning global variables)

>>> locals()
{&#39;__package__&#39;: None, &#39;__loader__&#39;: <class &#39;_frozen_importlib.BuiltinImporter&#39;>, &#39;__doc__&#39;: None, &#39;__name__&#39;: &#39;__main__&#39;, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__spec__&#39;: None}

>>> a = 1

>>> locals() # 多了一个key为a值为1的项
{&#39;__package__&#39;: None, &#39;__loader__&#39;: <class &#39;_frozen_importlib.BuiltinImporter&#39;>, &#39;a&#39;: 1, &#39;__doc__&#39;: None, &#39;__name__&#39;: &#39;__main__&#39;, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__spec__&#39;: None}

 2. Can be used within functions.

>>> def f():
    print(&#39;before define a &#39;)
    print(locals()) #作用域内无变量
    a = 1
    print(&#39;after define a&#39;)
    print(locals()) #作用域内有一个a变量,值为1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{&#39;a&#39;: 1}

 3. The returned dictionary set cannot be modified.

>>> def f():
    print(&#39;before define a &#39;)
    print(locals()) # 作用域内无变量
    a = 1
    print(&#39;after define a&#39;)
    print(locals()) # 作用域内有一个a变量,值为1
    b = locals()
    print(&#39;b["a"]: &#39;,b[&#39;a&#39;]) 
    b[&#39;a&#39;] = 2 # 修改b[&#39;a&#39;]值
    print(&#39;change locals value&#39;)
    print(&#39;b["a"]: &#39;,b[&#39;a&#39;])
    print(&#39;a is &#39;,a) # a的值未变

    
>>> f()
before define a 
{}
after define a
{&#39;a&#39;: 1}
b["a"]:  1
change locals value
b["a"]:  2
a is  1
>>>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:functools.wraps decoratorNext article:functools.wraps decorator