Python locals () and Globals ()

Source: Internet
Author: User

1, locals () and Globals () are Python's built-in functions that provide a way to access local and global variables in the form of dictionaries.

def test (ARG):
    a=1
    b=2
    data_dict = {}
    print locals ()
    print globals ()


if __name__ = ' __main__ ' :
    Test (3)

Output:

{' A ': 1, ' data_dict ': {}, ' B ': 2, ' arg ': 3}
{' __builtins__ ': <module ' __builtin__ ' (built-in), ' __file__ ': ' f:/work/workspace/pythonworkspace/learn/ locals_globals.py ', ' __package__ ': None, ' Test ': <function test at 0x0239f830>, ' __name__ ': ' __main__ ', ' __doc__ ': None}

2, locals () return is the current local variable deep copy, modify locals () The value of the variable, in fact, the original variable itself is not any effect. The Globals () returns a dictionary of global variables, modifying the contents of which the value will actually change.
Sample code:

b = 5 # define a global variable
def test2 ():
    a=1
    locals () ["a"] = 2  # Modify local variable
    print "A=", a
    globals () ["B"] = 6 # Modify global variable
    print "b=", b

if __name__ = = ' __main__ ':
    test2 ()

The output is:

A= 1
b= 6
Related Article

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.