Starting from local variables and global variables, the scope of variables in Python is fully parsed.

Source: Internet
Author: User
Tags closure definition variable scope

Starting from local variables and global variables, the scope of variables in Python is fully parsed.

Understand global variables and local variables
1. If the variable name in the defined function appears for the first time and before the = symbol, it can be considered as a local variable. In this case, whether or not the name of the global variable is used, the function uses local variables. For example:

  num = 100  def func():    num = 123    print num  func()

The output is 123. The variable name num defined in the function is a local variable that overwrites the global variable. For example:

  num = 100  def func():    num += 100    print num  func()

The output result is UnboundLocalError: local variable 'num' referenced before assignment. Error message: the local variable num is applied before the value assignment. That is to say, the variable is incorrectly used if it is not defined. This proves that the definition is a local variable, not a global variable.

2. If the variable name appears for the first time after the = symbol and has been defined as a global variable before, the global variable will be referenced here. For example:

  num = 100  def func():    x = num + 100    print x  func()

The output is 200. If the variable name num is not previously defined as a global variable, an error occurs: the variable is not defined. For example:

  def func():    x = num + 100    print x  func()

The output result is NameError: global name 'num' is not defined.

3. When a variable is used in a function, if the variable name contains both global and local variables, local variables are used by default. For example:

  num = 100  def func():    num = 200    x = num + 100    prinx x  func()

The output is 300.

4. When defining a variable as a global variable in a function, you must use the global keyword. For example:

  num = 100  def func():    global num    num = 200    print num  func()  print num

The output results are 200 and 200 respectively. This indicates that the variable name num in the function is defined as a global variable and assigned a value of 200. For example:

  num = 100  def func():    global num    num = 200    num += 100    print num  func()  print num

The output results are 300 and 300 respectively.

Based on the above results of the application scenarios of global variables and local variables, I tried to analyze the First Half of the Teaching code in input fields (a comment on the Chinese part ):

  # calculator with all buttons  import simplegui  # intialize globals  store = 0  operand = 0

The simplegui module is called here. You can operate it at http://www.codeskulptor.org/without error. However, this module cannot be used directly in the python environment. You need to install the SimpleGUICS2Pygame package first.

  # event handlers for calculator with a store and operand  def output():  """prints contents of store and operand"""    print "Store = ", store    print "Operand = ", operand    print ""

The global variables store and operand are directly used in the defined function output. For details, refer to the 2nd point.

  def swap():  """ swap contents of store and operand"""    global store, operand    store, operand = operand, store    output()

In the defined function swap (), global variables are defined for store and operand. If this operation is not performed, an error message is displayed, indicating that no value is assigned. For details, refer to the 1st point. In the swap () function, store and operand are local variables by default without the global keyword, while = the right part is used incorrectly if no value is assigned. For details, refer to the 3rd point.

  def add():  """ add operand to store"""    global store    store = store + operand    output()

Here I encountered the first problem since I took the course for two weeks: that is why the add () function only defines store as a global variable, but does not define operand in the same way. Now, we can see from the 1st point that store is not assigned a value in advance as a local variable and cannot be used directly. operand can be used directly by calling the previously defined global variables.

Variable Scope
Scope is an easy option in Python.
Python has four scopes:

L (Local) Local scope
E (Enclosing)
G (Global) Global SCOPE
B (Built-in) built-in Scope
Search by the L --> E --> G --> B rule, that is, if the local data cannot be found, the local data (such as the closure) is located outside the local data ), if you cannot find it, you will find it globally, and then you will find it in the inner process.

In addition to def/class/lambda, Python does not change its scope, for example, if/elif/else/try/else t for/while. Variables defined within them can still be accessed externally.

>>> if True:...   a = 'I am A'... >>> a'I am A'

Variable a defined in the if language is accessible externally.
However, if the if value is enclosed by def, class, or lambda, it becomes the local scope of this function, class, or lambda.
If a value is assigned within def/class/lambda, it becomes its local scope. The local scope will cover the global scope, but it will not affect the global scope.

G = 1 # global def fun (): g = 2 # partial return GPRS int fun () # result 2 print g # result 1

However, you must note that if you want to reference global variables in a function, errors may occur if you are negligent. For example:

#file1.pyvar = 1def fun():  print var  var = 200print fun()#file2.pyvar = 1def fun():  var = var + 1  return varprint fun()

Both functions report the following error: UnboundLocalError: local variable 'var' referenced before assignment.
An error that is referenced before being assigned a value! Why? In the function, the interpreter detects that var has been assigned a value again, so var becomes a local variable. However, if you want to use var before being assigned a value, this error will occur. The solution is to add globals var to the function, but the global var will be modified after the function is run.

Closure
Closure definition: If a variable in an internal function is referenced in an external function (but not in a global scope), the internal function is considered as a closure)

Scope in function nesting/closure:

a = 1def external():  global a  a = 200  print a  b = 100  def internal():    # nonlocal b    print b    b = 200    return b  internal()  print bprint external()

In the same way, an error will be reported-before the reference is assigned, Python3 has a keyword nonlocal to solve this problem, but in Python2, do not try to modify the variables in the closure. There is also a pitfall in the closure:

from functools import wrapsdef wrapper(log):  def external(F):    @wraps(F)    def internal(**kw):      if False:        log = 'modified'      print log    return internal  return external@wrapper('first')def abc():  passprint abc()

There will also be an error before the value is referenced, because the interpreter detects the re-assignment in if False, so it will not find the variable in the external function of the closure (Enclosing, however, if Flase is not set and is not executed, this error occurs. Unless you still need else: log = 'var' or if True, but adding the logical statement in this way makes no sense, so try not to modify the variables in the closure.

It seems that the regular method cannot enable the closure to implement the counter function, because the internal count + = 1 will cause the error before the value assignment, solution: (or the nonlocal keyword in the Py3 environment)

def counter(start):    count =[start]    def internal():      count[0] += 1      return count[0]    return internalcount = counter(0)for n in range(10):  print count()# 1,2,3,4,5,6,7,8,9,10count = counter(0)print count()# 1

Because the list is variable, the string type is not variable.

Locals () and globals ()
Globals ()
Global and globals () are different. global is a keyword used to declare a local variable as a global variable. Globals () and locals () provide dictionary-based access to global and local variables

For example, if function 1 needs to define a local variable with the same name as function 2, but function 2 must be referenced in function 1.

def var():  passdef f2():  var = 'Just a String'  f1 = globals()['var']  print var  return type(f1)print f2()# Just a String# <type 'function'>

Locals ()
If you have used a Python Web framework, you must have passed many partial variables in a view function to the template engine and then applied them to HTML. Although you can do something smarter, you still want to pass many variables at a time. You don't need to know how these syntaxes come from. You just need to know what locals () is.
As you can see, locals () has packed all the local variables and threw them together.

@ App. route ('/') def view (): user = User. query. all () article = Article. query. all () ip = request. environ. get ('HTTP _ X_REAL_IP ', request. remote_addr) s = 'just a String 'return render_template('index.html', user = user, article = article, ip = ip, s = s) # Or return render_template('index.html ', ** locals ())

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.