Python Basics: Namespaces and scopes

Source: Internet
Author: User

Python's variables are defined with their own scopes, with namespaces within each scope. A namespace is an association between a variable name and an object. Python uses variable names to refer to objects, and when that variable is used, it is searched in the namespace to get the corresponding object. From the current implementation of Python, the internal use of the dictionary, but there is no guarantee that the implementation will change, so at this stage, the namespace is a dictionary (dictionary), its key is the variable name, its value is the value of those variables. There are at least 4 scopes in a Python program running.

Direct access to a variable may be searched in one of these four namespace.

    • Local (innermost)

      Contains local variables.
      such as a function/method inside.

    • Enclosing

      Variables that contain non-local (non-local) and non-Global (Non-global).
      For example, two nested functions, the inner layer function may search for the namespace of the outer function, but the namespace is neither local nor global to the inner layer function.

    • Global (Next-to-last)

      The outermost layer of the current script.
      such as the global variables of the current module.

    • Built-in (Outtermost)

      Python __builtin__ module.
      Contains built-in variables/keywords, etc.

So, so many scopes, what order does Python search for the corresponding scopes?

The famous "Legb-rule", that is, the scope of the search order:

Built-in, Global, enclosing, Local

Each function has its own namespace, called the local namespace;

The outer namespace of each local namespace, called the enclosing area , is the enclosing area of the inline function, such as the local namespace of the outer function of the inline function.

Each module has its own namespace, called the global namespace ;

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

When a variable is not found in the local domain, Python will look for a previous level of scope, that is, the enclosing domain (which does not necessarily exist).
When the enclosing field is not found yet, go up one level and search for the global domain within the module. Finally, the search is in the built-in domain.
Python throws an exception when there is no final search NameError .

The case of nested functions:

1, first in the current (nested or lambda) function of the namespace search 2, and then in the parent function of the namespace search 3, followed by the module namespace Search 4, and finally in the built-in namespace search

1. The global scope has a global namespace that is generated when the program starts running, disappears when the program exits, and can access the global namespace through the Globals () function or dir ("__main__").

2. Function-defined function body is the local namespace, generated when the function is called, disappears at the end of the call, call locals () in the function body can access the local namespace. One of the very strange phenomena in Python is that the global keyword is used to declare a variable in the function body , because there is a local assignment rule in Python. For example:

Globalvar = 2def MyFunc (): Globalvar = Globalvar + 2print Globalvar

The above code throws "Unboundlocalerror:local variable ' globalvar ' referenced before assignment" exception, requiring the variable to be assigned first.

If you assign a value to a variable in the body of a function, Python Adds the name to the local namespace, and when performing operations on the right, it finds that there are globalvar in the local namespace, tries to add the Globalvar to 1, and Globalvar in the local namespace has not been assigned a value. Will throw an exception .

Globalvar = 2def MyFunc (): Global Globalvarglobalvar = Globalvar + 2print Globalvar

Declaring Globalvar as a global variable resolves the above problem.

3. Encolsing the namespace of the function variable. In short, it is the local namespace of the new function defined in the function body.

Globalvar = 2def MyFunc (): Funvar = 3def innerfunc (): Innervar = 4INNERVAR2 = Funvarprint ' inner locals: ' + str (locals ()) #pr int ' inner globals: ' + str (globals ()) Innerfunc () print ' outer locals: ' + str (locals ()) #print ' outer globals: ' +str (Globals ())

The output of the global function is omitted here:

Inner locals:{' Funvar ': 3, ' innerVar2 ': 3, ' Innervar ': 4}outer locals:{' Funvar ': 3, ' Innerfunc ': <function innerfunc at 0x0000000007bbc4a8>}

It can be seen that the inner function name is part of the external function's local namespace, and the intrinsics find the local namespace first, and then the local namespace of the outer function (enclosing area enclosing) , and then the global variable , and finally in the built-in module namespace to find.

4. Built-in module namespaces. When Python starts, the __builtins__ module is created automatically, and the Python data type is defined in the module. Following the LEGB search rule, if Python cannot find a name in the local namespace, it will continue to look for it in the global namespaces, and then find it in the built-in module. The name of the built-in module can be obtained via __builtins__.__dict__.

Finally, Python uses the property lookup method in Object-oriented programming:

The first thing to know: in a sense, all the properties of an object (attribute) also constitute a namespace.

A. About property lookup methods for class types and class instance objects. For example, the following definitions:

If no related property is found in the instance object, it is found in the namespace of the class type, but conversely, a property that is not found in the class type will not be looked up in the associated instance object namespace. This is also easier to understand, after all, the class type is a one-to-many relationship with the class instance.

There's another subtle place to stress here. Once the properties of an instance object are defined, the properties defined in the class type namespace are overwritten. Look at the following example:

Class Base (object): var = ' Hello ' obj1 = base () Obj1.var = ' world ' Obj2 = base () print ' obj1 value = ' + str (obj1.var) + ' | id = ' + str (ID (obj1.var)) print ' obj2 value = ' + str (obj2.var) + ' | id = ' + str (ID (obj2.var)) print ' Base value = ' + str (base.var) + ' | id = ' + str (ID (base.var))

Execution Result:

B. Properties of a subclass instance object if it is not found in the instance object , look in the subclass type namespace First, and then look in the namespace of the parent class.

Class Pythonbase (object): varbase = ' Foo ' class Derived (pythonbase):p assderivedobj = Derived () print Derivedobj.varbase

Python Basics: Namespaces and scopes

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.