Python function scope (python3.5), pythonpython3.5

Source: Internet
Author: User

Python function scope (python3.5), pythonpython3.5
1 Basic Concept 1.1 namespace)

The namespace is the ing from the variable name to the object (name-> obj ). Currently, most namespaces are implemented in the form of a python dictionary, and the Implementation form may change in the future. Namespace example: built-in variables (built-in functions abs, built-in exceptions, etc.), global variables in the module, and local variables used for function calls. In a sense, object attributes also form a namespace. Importantly, there is no association between variables in different namespaces. Two different namespaces can contain the same variable name.

Namespaces have different creation times and lifecycles:

  • The built-in variable namespace is created when the python interpreter is started and will never be deleted while the interpreter is running;
  • The namespace of a module is created when the module is imported and will exist until the interpreter exits;
  • The local (local) namespace of the function is created when the function is called and deleted when the function exits;
  • The statements executed at the top layer of the interpreter are all part of the _ main _ module, and they have their own namespaces.

Note: built-in variables actually exist in the form of modules. The module name is builtins.

1.2 scope)

The scope is the text area of a namespace variable that can be directly accessed in a Python program. It can be directly accessed that the variables in the namespace are visible and can be referenced in the text area.

  • Local (local) Scope: internal function or class
  • Global scope: the running environment of the entire program.

Variables defined in the local scope cannot be directly accessed in the global scope:

def func1():    name = 1print(func1)    # <function func1 at 0x101a03d08>print(name)# Traceback (most recent call last):#   File "<stdin>", line 1, in <module># NameError: name 'name' is not defined

 

Variable definitions in local scopes:

  • In python, variable assignment is defined. Variables assigned in the local scope are all local variables unless declared by global or nonlocal. The function is called in the function namespace.
  • Global var: Declares the variable var as a global variable. All its references and assignments are carried out in the module namespace.
  • Nonlocal var: bind the variable var in The namespace of the outer function to the local scope so that it can be assigned a value in the local scope. If the variables are not declared as nonlocal, they are only readable in the local scope. If you try to assign a value to the variables, a variable with the same name will be created in the local namespace.

Variables declared by nonlocal must exist in upper-layer functions; otherwise, an error is returned:

1 test = 'global variable'2 3 def scope_test():4     def inner():5         nonlocal test6         print(test)7 8 scope_test()    # SyntaxError: no binding for nonlocal 'test' found
2 example 2.1 search for variables in the local scope follows the LEGB rule
1 def scope_test (): 2 def do_local (): 3 spam = "local spam" 4 5 def do_nonlocal (): 6 nonlocal spam # Recursively search for the spam variable 7 spam = "nonlocal spam" 8 9 def do_global (): 10 global spam # search for the spam variable in the global variable, if no, create 11 spam = "global spam" 12 13 spam = "test spam" 14 do_local () 15 print ("After local assignment:", spam) # output local variable spam16 do_nonlocal () 17 print ("After nonlocal assignment:", spam) 18 do_global () 19 print ("After global assignment:", spam) 20 21 scope_test () 22 print ("In global scope:", spam)

Result

1 After local assignment: test spam2 After nonlocal assignment: nonlocal spam3 After global assignment: nonlocal spam4 In global scope: global spam
2.2 Closure

Closure: in nested functions, if the inner function references the variable of the outer function, a closure is formed.

Free variable: The referenced outer function variable, called the free variable of the inner function.

def fn():    a = 1    def closure():        nonlocal a        a += 1        print(a)    return closureinner = fn()  print(inner.__closure__)    # (<cell at 0x10240b408: int object at 0x100277bc0>,)inner()  # 2inner()  # 3

After the outer function is executed, its namespace is deleted. However, because a is a free variable of the inner function, variable a is retained and can be considered as an additional attribute of the closure function object.

3. Static detection of 3.1 local variables

Python static checks its local variables when compiling def statements.

a = 1def local_test():    a += 1    print(a)local_test()    # UnboundLocalError: local variable 'a' referenced before assignmentprint(b)    # NameError: name 'b' is not defined

When compiling the local_test function, python determines that variable a is the local variable of the function. Therefore, executing a + = 1 directly searches for variable a in the local namespace.

3.2 namespace search chain
name = "lzl" def f1():    print(name) def f2():    name = "eric"    f1() f2() # lzl

 

The variable search path of a function is determined when it is defined and is not affected by its call location.

When f1 is defined in the global scope, its variable search path is: local namespace --> module namespace. Therefore, the final output result is 'lzl '.

 

4. Anonymous Functions

Python defines anonymous functions with lambda keywords in the following format:

Lambda parameter list: Expression

Lambda x: x + 1
# Function type in the following function def _ (x): return x + 1
Example

What is the output result of the following code:

 1 li = [lambda :x for x in range(10)] 2 print(li[0]())

 

Equivalent form:

1 def fn (): 2 return x 3 4 li = [] 5 for x in range (10): 6 li. append (fn) 7 li [0] () # fn ()-> 9. According to the variable search rule, x is not defined in the function and is searched in the global variable.

 

 

 

Refer:

[1] http://www.cnblogs.com/livingintruth/p/3296010.html

[2] file: // Library/Frameworks/Python. framework/Versions/3.5/Resources/English. lproj/Documentation/tutorial/classes.html # id2

[3] http://python.jobbole.com/86465/

 

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.