Interpretation of namespaces and scopes in Python Programming

Source: Internet
Author: User
This article mainly introduces the namespace and scope in Python programming. it is an important knowledge in getting started with Python. if you need a variable, you can refer to it as the name (identifier) of the matching object ). A namespace is a dictionary containing variable names (keys) and their corresponding objects (values.
A Python expression can access the variables in a local namespace and a global namespace. If a local variable and a global variable have the same name, the local variable overwrites the global variable.
Each function has its own namespace. The scope rules of class methods are the same as those of common functions.
Python intelligently guesses whether a variable is local or global. it assumes that any variable assigned a value in the function is local.
Therefore, to assign a value to a global variable in a function, you must use the global statement.
The global VarName expression tells Python that VarName is a global variable, so that Python will not find this variable in a local namespace.

Namespace Definition
The Python namespace is the ing between names and objects, which is like a dictionary. The key name is the variable name and the value is the value of the variable. For example:

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

The variables x and 3 are stored in the globals space in a dictionary. The corresponding namespace is also: locals ().

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

In fact, you can add the key name and value to the name:

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

There is a built-in namespace on the left, and different modules on the right have their own global namespaces. the functions defined in the global namespace will have a local namespace.

Namespace type
Python has three namespaces:

A) Local: the namespace in the function is local;
B) global: the namespace in the module is global;

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


Next we will discuss the search sequence of namespace. let's take a look at the figure:

Namespace visibility (SCOPE)
A) the built-in namespace is visible in all locations of the code, so it can be called at any time;

B) if a variable with the same name exists in a global namespace or a local namespace, the variables with the same name in the local namespace are invisible;

C) in a local namespace, variables with the same name in the global namespace are invisible (only when the variables have different names can be visible using the global keyword ).

With visibility, the search sequence of variables is much clearer.


Query order of namespaces
A) if a variable is called in the function, first search in the function (local namespace). if it is found, stop searching. Otherwise, search outside the function (global namespace). If not, search for the built-in namespace. If none of the above three names are found, the NameError exception is thrown.
B) if a variable is called outside the function, search outside the function (global namespace, local namespace is not visible at this time). if it is found, stop searching, otherwise, search in the built-in namespace. If neither of them is found, an exception is thrown. Only when a variable is declared using the global keyword in a local namespace, the search order is.


For better understanding, let's take an example. we define a variable money in the global namespace. We then assign values to the variable money in the function, and Python assumes that money is a local variable. However, we did not declare a local variable money before the access. The result is an UnboundLocalError error. This problem can be solved by canceling the comments of the global statement.

#! /Usr/bin/python #-*-coding: UTF-8-*-Money = 2000def AddMoney (): # Remove the following comments if you want to correct the code: # global Money = Money + 1 print MoneyAddMoney () print Money

Dir () function
The dir () function is a sorted string list with the name defined in a module.
The returned list contains all the modules, variables, and functions defined in a module. For example, the following simple example:

#! /Usr/bin/python #-*-coding: UTF-8-*-# import the built-in math module import math content = dir (math) print content;

Output result of the above instance:

['__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 module name, __file _ points to the imported file name of the module.

Globals () and locals () functions

  • Depending on the call location, the globals () and locals () functions can be used to return names in global and local namespaces.
  • If locals () is called within the function, all the names that can be accessed in the function are returned.
  • If globals () is called within the function, all global names that can be accessed in the function are returned.
  • The return types of both functions are Dictionary. So the names can be extracted using the keys () function.

Reload () function
When a module is imported to a script, the code at the top layer of the module is executed only once.
Therefore, if you want to re-execute the code at the top layer of the module, you can use the reload () function. This function re-imports the previously imported modules. Syntax:

reload(module_name)


Here, module_name should be placed directly with the module name, rather than a string. For example, you want to overload 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.