Python built-in function locals

Source: Internet
Author: User
English documents:

Locals ()

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

Description

1. Function function returns a dictionary of local variables and their values in the current scope, similar to the GLOBALS function (returns a global variable)

>>> locals () {' __package__ ': None, ' __loader__ ': 
 
  
   
  , ' __doc__ ': None, ' __name__ ': ' __main__ ', ' __ Builtins__ ': 
  
   
    
   , ' __spec__ ': none}>>> a = 1>>> locals () # More than one key for a value of 1 {' __package__ ': None, ' __loader__ ': 
   
    
     
    , ' a ': 1, ' __doc__ ': None, ' __name__ ': ' __main__ ', ' __builtins__ ': 
    
     
      
     , ' _ _spec__ ': None}
    
     
   
    
  
   
 
  

2. Can be used in functions.

>>> def f (): print (    ' before define a ')    print (Locals ()) #作用域内无变量    a = 1    print (' after define A ')    print (Locals ()) #作用域内有一个a变量 with a value of 1    >>> f
 
  
   
  >>> F () before define a {} after Define a{' a ': 1}
 
  

3. The returned dictionary collection cannot be modified.

>>> def f (): Print    (' before define a ')    print (Locals ()) # in scope no variable    a = 1    print (' after define a ') 
  print (Locals ()) # has an A variable in the scope with a value of 1    b = locals ()    print (' b["a"]: ', b[' a '])     b[' a '] = 2 # Modify the b[' a '] value    print ( ' Change locals value ')    print (' b["a"]: ', b[' a '])    print (' A is ', a) # value unchanged    >>> f () before define a {} After define a{' a ': 1}b["a"]:  1change 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.