Python basic tutorial built-in functions locals () and globals () Usage Analysis, pythonglobals

Source: Internet
Author: User

Python basic tutorial built-in functions locals () and globals () Usage Analysis, pythonglobals

This example describes the usage of the built-in functions locals () and globals () in the basic Python tutorial. We will share this with you for your reference. The details are as follows:

1. These two functions provide dictionary-based access to local variables and global variables.

Python uses something called a namespace to record the trajectory of a variable. A namespace is a dictionary. Its key is a variable name in the form of a string, and its value is the actual value of the variable.

The namespace can be accessed like a Python dictionary.

There are several available namespaces in any part of a Python program.

Each function has its own namespace, called a local namespace. It records function variables, including function parameters and locally defined variables.

Each module has its own namespace, which is called a global namespace. It records module variables, including functions, classes, other imported modules, module-level variables, and constants.

There is also a built-in namespace, which can be accessed by any module. It stores built-in functions and exceptions.

2. When a line of code uses the value of variable x, Python searches for variables in all available namespaces in the following order:

Local namespace-This refers to the method of the current function or class. If a function defines a local variable x or a parameter x, Python uses it and then stops searching.

Global namespace-specifies the current module. If the module defines a variable, function, or class named x, Python uses it and then stops searching.

Built-in namespace-Global for each module. As a final attempt, Python assumes that x is a built-in function or variable.

If Python cannot find x in these namespaces, it will discard the lookup and raise a NameError exception, and pass a message like There is no variable named 'x.

3. The namespace can be accessed directly at runtime. The local namespace can be accessed through the built-in locals function. The global (module-level) namespace can be accessed through the built-in globals function.

Locals does something for the local (function) namespace, and globals does something for the global (module) namespace.

However, globals is even more excited because the namespace of a module contains module-level variables and constants. It also includes all functions and classes defined in the module, and anything imported into the module.

4. Think about the differences between from module import and import module?

When using the import module, the module itself is imported, but it maintains its own namespace, Which is why you need to use the module name to access its function or attribute: module. function.

However, using from module import actually imports the specified functions and attributes into your own namespace from another module, this is why you can directly access them without referencing the modules from which they are sourced.

Using the globals function, you can see exactly what happened.

5.locals()Instance:

def foo(arg, a):  x = 100  y = 'hello python!'  for i in range(10):    j = 1    k = i  print locals()foo(1,2)

Result:

{'a': 2, 'i': 9, 'k': 9, 'j': 1, 'arg': 1, 'y': 'hello python!', 'x': 100}

6. locals is read-only and cannot be modified. globals can be modified because:

locals()Actually, no local namespace is returned. It returns a copy. Therefore, it is modified by copying, but it does not affect the variable value in the actual local namespace.

globals()The actual global namespace is returned, rather than a copy: it is the opposite of locals.

Therefore, any change to the dictionary returned by globals will directly affect the value of the global variable.

#! /Usr/bin/env python # coding: UTF-8 ''' This is my first python program! '''Z = 7 # define the global variable def foo (arg): x = 1 print locals () print 'X = ', x locals () ['X'] = 2 # modify the copy of a local namespace, but the variable values in the actual local namespace are not affected. Print locals () print "x =", xfoo (3) print globals () print 'z = ', zglobals () ["z"] = 8 # globals () the actual global namespace is returned, and the value of variable z is changed to print globals () print "z =", z

Result:

{'x': 1, 'arg': 3}x= 1{'x': 1, 'arg': 3}x= 1{'foo': <function foo at 0x02A17CF0>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'E:\\workspace\\python day03\\main\\test.py', '__package__': None, '__name__': '__main__', 'z': 7, '__doc__': 'This is my first python program!'}z= 7{'foo': <function foo at 0x02A17CF0>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'E:\\workspace\\python day03\\main\\test.py', '__package__': None, '__name__': '__main__', 'z': 8, '__doc__': 'This is my first python program!'}z= 8

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.