Python built-in function locals

Source: Internet
Author: User
Python built-in functions locals English document:

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.

Note:

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

>>> Locals () {'_ package _': None, '_ loader __':
 
  
, '_ Doc _': None, '_ name _': '_ main _', '_ builtins __':
  
   
, '_ Spec _': None }>>> a = 1 >>> locals () # an additional item {'_ package _': None, '_ loader _' with a key of 1 is added __':
   
    
, 'A': 1, '_ doc _': None, '_ name _': '_ main __', '_ builtins __':
    
     
, '_ Spec _': None}
    
   
  
 

2. it can be used in functions.

>>> Def f (): print ('before define a') print (locals () # no variable a = 1 print ('After define a') in the scope ') print (locals () # There is a variable a in the scope. The value is 1 >>> f
 
  
>>> F () before define a {} after define a {'a': 1}
 

3. the returned dictionary set cannot be modified.

>>> Def f (): print ('before define a') print (locals () # no variable a = 1 print ('After define a') in the scope ') print (locals () # There is a variable a in the scope. The value is 1 B = locals () print ('B ["a"]:', B ['A']) B ['A'] = 2 # modify B ['A'] value print ('change locals value ') print ('B ["a"]:', B ['A']) print ('A', a) # The value of a has not changed >>> f () before define a {} after define a {'a': 1} B ["a"]: 1 change locals valueb ["a"]: 2a is 1 >>>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.