Python Scopes and namespaces

Source: Internet
Author: User

Before introducing classes, I First has a to-tell you something about Python's scope rules. Class definitions play some neat tricks with namespaces, and what need to know how scopes and namespaces work to fully unde Rstand ' s going on. Incidentally, knowledge about this subject was useful for any advanced Python programmer.

Let's begin with some definitions.

namespace  is A mapping from names to objects. Most namespaces is currently implemented as Python dictionaries, but that's normally not noticeable on any (except fo R performance), and it may change in the future. Examples of namespaces are:the set of built-in names (containing functions such as abs () , and built-in exception names); The global names in a module; And the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. The important thing to know about namespaces are that there are absolutely no relation between names in different namespaces ; For instance, the different modules may both define a function  Maximize  without confusion-users of the modules must prefix it with the module name.

By the the-the-word  attribute  for any name following a dot-for example, in the EXPRESSION&N Bsp z.real ,  < Span class= "Pre" >real  is an attribute of the Object z . Strictly speaking, references to names in modules is attribute references:in the Expression modname.funcname ,   modname  is a Module object and funcname  is An attribute of it. There happens to is a straightforward mapping between the module ' s attributes and the global names defined in The Module:they share the same namespace! [1]

Attributes may read-only or writable. In the latter case, assignment to attributes is possible. Module attributes is writable:you can write modname.the_ Answer = 42 . Writable attributes may also is deleted with The del  statement. For Example, del modname.the_ Answer  will Remove the Attribute < Span class= "Pre" >the_answer  from The object named By modname .

Namespaces is created at different moments and has different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module was created when the module definition was read in; Normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, a Re considered part of a module Called __main__< /span> , so they has their own global namespace. (The built-in names actually also live in a module; this is Called  builtins .)

The local namespace for a function was created when the function was called, and deleted when the function returns or raises An exception, that's not handled within the function. (Actually, forgetting would be a better-to-describe what actually happens.) Of course, recursive invocations each has their own local namespace.

A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" here means, a unqualified reference to a name attempts to find the name in the namespace.

Although scopes is determined statically, they is used dynamically. At any time during execution, there is at least three nested scopes whose namespaces is directly accessible:

    • the innermost scope, which was searched first, contains the local names
    • the scopes of an Y enclosing functions, which is searched starting with the nearest enclosing scope, contains non-local, but also Non-glob Al names
    • the next-to-last scope contains the current module ' s global names
    • the outermost scope (search Ed last) is the namespace containing built-in names

If a name is declared global, then all references and assignments go directly to the middle scope containing the module ' s Global names. To rebind variables found outside of the innermost scope, the nonlocal statement can is used; if not declared nonlocal, those Variable is read-only (an attempt to write to such a variable would simply create a new local variable in the Nermost scope, leaving the identically named outer variable unchanged).

Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the Global scope:the module ' s namespace. Class definitions Place yet another namespace in the local scope.

It is important to realize that scopes be determined textually:the global scope of a function defined in a module is That's module ' s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names are done dynamically in run time-however, the language definition is Evol Ving Tsun towards static name resolution, at "compile" time, so don ' t rely on dynamic name resolution! (In fact, local variables is already determined statically.)

A Special Quirk of Python is that–if no  global  statement is in effect–assignments to names all go into the innermost scope. Assignments don't copy data-they just bind names to objects. The same is true for deletions:the statement del x  removes The binding of  x  from the namespace referenced by the local scope. In fact, all operations this introduce new names use the local scope:in particular, import  statements and function definitions bind the module or Function name in the local scope.

The global statement can used to indicate, particular variables live in the global scope and should be rebound there ; The nonlocal statement indicates that particular variables live in a enclosing scope and should be rebound there.

This is a example demonstrating how to reference the different scopes and namespaces, and how global and nonlocal affect vari Able Binding:

DefScope_test():DefDo_local():Spam="Local spam"DefDo_nonlocal():NonlocalSpamSpam="Nonlocal spam"DefDo_global():GlobalSpamSpam="Global spam"Spam= "test spam" do_local () print span class= "S2" > "after local assignment:" spam do _nonlocal () print ( "after nonlocal assignment:" Span class= "P", spam) do_global () print ( "after global assignment:" spam) scope_test () print  ( "in global scope:" spam  

The output of the example code is:

After local assignment:test spamafter nonlocal assignment:nonlocal spamafter Global assignment:nonlocal spamIn global S Cope:global spam

Note how the local assignment (which are default) didn ' t change scope_test' s binding of spam. nonlocalthe assignment changed scope_test' s binding of spam, and the assignment changed the Module-l global Evel binding.

You can also see that there is no previous binding for spam before the global assignment.

Python Scopes and namespaces

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.