Interpreting namespaces and scopes in Python programming

Source: Internet
Author: User
A variable is a name (identifier) that has a matching object. A namespace is a dictionary that contains the variable names (keys) and their respective objects (values).
A Python expression can access variables in the local namespace and in the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.
Each function has its own namespace. The scope rules of a method of a class are the same as the usual functions.
Python intelligently guesses whether a variable is local or global, and assumes that any variable that is assigned within the function is local.
Therefore, if you want to assign a value to a global variable in a function, you must use the global statement.
The expression for global varname tells Python that VarName is a global variable so that Python does not look for the variable in the local namespace.

Definition of namespaces
A Python namespace is a name-to-object mapping, which is like a dictionary, where the key name is the variable name and the value is the value of the variable. Like what:

>>> x = 3>>> globals () {' __builtins__ ': 
 
  
   
  , ' __name__ ': ' __main__ ', ' __doc__ ': None, ' x ': 3, ' __package__ ': None}
 
  

You can see that the variable x,3 is stored in the Globals space in the form of a dictionary. The corresponding namespaces are also: locals ().

>>> locals () {' __builtins__ ': 
 
  
   
  , ' __name__ ': ' __main__ ', ' __doc__ ': None, ' x ': 3, ' __package__ ': None}
 
  

In fact, you can add key names and values by adding names to the name:

>>> globals () [' y '] = 5>>> Y5

On the left is the built-in namespace, the right side is a different module, there is a separate global namespace, and the definition function within the global namespace has a local namespace.

Types of namespaces
There are three types of namespaces in Python:

A) Local, the namespace within the function is local;
b) Globally, the namespace within the module is global;

c) built-in, including exception types, built-in functions and special methods, can be called anywhere in the code;


The following is a discussion of the search order for namespaces, with a first look at the diagram:

Visibility of namespaces (scopes)
A) The built-in namespaces are visible at all locations in the code, so they can be called at any time;

b) In the global namespace and local namespace, if there is a variable with the same name, at the global namespace, the variable with the same name in the local namespace is not visible;

c) At the local namespace, a variable of the same name in the global namespace is not visible (the Global keyword can be used to make it available only if the variable name is different).

Know the visibility, the following is said to find the order of the variables are much clearer.


Lookup Order of namespaces
A) If a variable is called within a function, it is first found within the function (the local namespace), and the lookup is stopped if it finds it. Otherwise, look outside the function (global namespace), and if not, find the built-in namespace. If none of the above three names are found, a Nameerror exception error is thrown.
b) If a variable is used outside of the function, it is looked out of the function (the global namespace, the local namespace is not visible at this time), and if found, stops the lookup, otherwise to the built-in namespace. If neither is found, an exception is thrown. The lookup order is found only if a variable is declared with the Global keyword within the local namespace, and the lookup order is a.


To help understand, for example, we define a variable money in the global namespace. We then assign a value to the variable money within the function, and then Python assumes that money is a local variable. However, we did not declare a local variable money before the visit, and the result is a unboundlocalerror error. Canceling the comment on the global statement will solve this problem.

#!/usr/bin/python#-*-coding:utf-8-*-money = 2000def Addmoney ():  # To correct the code, uncomment the following:  # global Money money  = Mo Ney + 1 Print moneyaddmoney () print money

Dir () function
The Dir () function is a well-ordered list of strings, and the content is a name defined in a module.
The returned list contains all the modules, variables, and functions defined in a module. Here is a simple example:

#!/usr/bin/python#-*-coding:utf-8-*-# Importing built-in math module import Math content = Dir (math) print content;

The result of the above example output:

[' __doc__ ', ' __file__ ', ' __name__ ', ' ACOs ', ' asin ', ' atan ', ' atan2 ', ' ceil ', ' cos ', ' cosh ', ' degrees ', ' e ', ' exp ', ' fabs ', ' Floor ', ' fmod ', ' frexp ', ' hypot ', ' ldexp ', ' Log ', ' log10 ', ' modf ', ' pi ', ' pow ', ' radians ', ' sin ', ' sinh ', ' sqrt ', ' tan ', ' Tanh ']

Here, the special string variable __name__ points to the name of the module, and __file__ points to the import file name of the module.

Globals () and locals () functions

    • Depending on where they are called, the Globals () and locals () functions can be used to return names in the global and local namespaces.
    • If locals () is called inside the function, all the names that can be accessed in the function are returned.
    • If Globals () is called inside the function, all the global names that can be accessed in the function are returned.
    • The return type of two functions is a dictionary. So names can be extracted with the keys () function.

Reload () function
When a module is imported into a script, the code at the top-level part of the module is executed only once.
Therefore, if you want to re-execute the code in the top-level part of the module, you can use the reload () function. The function will re-import the previously imported modules. The syntax is as follows:

Reload (module_name)


Here, module_name to directly put the module's name, not a string form. For example, to reload the Hello module, as follows:

Reload (Hello)
  • 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.