Resolving the scope of variables in Python from local variables and global variables

Source: Internet
Author: User
Tags closure definition variable scope
Whether it is a class-based face object programming, or a simple function of the definition of internal variables, the scope of the variable is always a Python learning must understand the link, the following we start from the local variables and global variables to fully parse the scope of the python variables, the need for friends can refer to the next

Understanding global variables and local variables
1. The variable name inside the defined function is assumed to be defined as a local variable if it is first present and before the = sign. In this case, a local variable is used in the function, regardless of whether the variable name is used in the global variable. For example:

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

The output result is 123. The variable name defined in the description function num is a local variable that overrides the global variable. Again for example:

  num =  + def func ():    num + =    -Print num  func ()

The output is: unboundlocalerror:local variable ' num ' referenced before assignment. Hint Error: The local variable num is applied before the value is assigned. This means that the variable is not defined and is used incorrectly. This again proves that a local variable, not a global variable, is defined here.

2. If the variable name inside the function appears for the first time and appears after the = symbol and has been previously defined as a global variable, then the global variable is referenced here. For example:

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

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

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

The output is: Nameerror:global name ' num ' was not defined.

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

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

The output result is 300.

4. Use the keyword global when defining a variable as a global variable in a function. For example:

  num = +  def func ():    global num    num = $    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 is assigned a value of 200. Again for example:

  num = +  def func ():    global num    num = $    num + = +    print num  func ()  print num

The output results are 300 and 300, respectively.

Combining the results of the previous scenarios for global variables and local variables, I tried to do some analysis of the first half of the teaching code in input fields (the Chinese part of the note):

  # Calculator with all buttons  import Simplegui  # intialize globals  store = 0  operand = 0

The Simplegui module is called here and can be operated correctly in http://www.php.cn/. However, the module cannot be used directly in the Python environment, and the Simpleguics2pygame package needs to be installed 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 used directly in the defined function output (). Refer to 2nd.

  Def swap (): "" "Swap contents of store and operand" "" "    Global store, operand    store, operand = operand, store
  output ()

In the defined function swap () First, the store and operand are defined as global variables. If this is not the case, then there will be an error message that is used without assignment. Refer to 1th. It is also not possible to understand this: in function swap (), in the absence of the keyword Global, store and operand are the default local variables, while the right side of the non-assignment is used incorrectly. Refer to 3rd.

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

Here I came across the first puzzle since the two-week course: That's why the Add () function defines only the store as a global variable, and not the same definition of operand. Now in the 1th, it is because the store is not assigned in advance as a local variable and cannot be used directly, whereas operand can be used directly by calling the previously defined global variables.

Variable scope
Variable scope (scope) is an easy place to drop holes in python.
There are 4 scopes in Python, namely:

L (local) local scope
In functions outside of the E (enclosing) closure function
G (Global) scope
B (built-in) built-in scopes
With the rules of L-E-and G--->b, that is: in the local can not find, will go to local outside the local search (such as closures), and can not find the overall look, and then to the built-in search.

In addition to Def/class/lambda, Python, such as the if/elif/else/try/except For/while, cannot change its scope. Variables defined within them can be accessed externally.

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

Variable A, defined in the if language, can be accessed externally.
However, it is important to note that if the IF is DEF/CLASS/LAMBDA wrapped and assigned internally, it becomes the local scope of this function/class/lambda.
Assignment within a DEF/CLASS/LAMBDA becomes its local scope, and the local scope overrides the global scope without affecting the global scope.

g = 1 #全局的def fun ():  g = 2 #局部的  return gprint fun () # result is 2print g# result is 1

However, it is important to note that sometimes you want to refer to global variables inside a function, and errors occur when you neglect them, such as:

#file1. Pyvar = 1def Fun ():  print var  var = 200print fun () #file2. Pyvar = 1def Fun ():  var = var + 1  return V Arprint Fun ()

Both functions will be error unboundlocalerror:local variable ' var ' referenced before assignment
The error that was referenced before the value was assigned! Why? Because in the inside of the function, the interpreter detects that Var is being re-assigned, so VAR becomes a local variable, but the error occurs when you want to use Var before it is assigned. The workaround is to add globals Var inside the function but the global VAR will also be modified after the function is run.

Closed Bag closure
Closure definition: If a reference is made to a variable within an external function (but not at the global scope) in an intrinsic function, then the intrinsic function is considered a closure (closure)

Scopes in function nesting/closures:

A = 1def external ():  Global a  = $  print a  b =  def internal ():    # nonlocal b    Print b
  b =    return B  internal ()  print bprint external ()

Same error-Reference before assignment, Python3 has a keyword nonlocal to solve the problem, but in Python2 do not try to modify the variables in the closure. There is also a hole 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 a reference to the error before the assignment, because the interpreter detects the re-assignment in if False, so it does not look for the variable in the outer function of the closure (enclosing), but if Flase is not executed, this error occurs. Unless you also need to else:log= ' var ' or if True but it doesn't make sense to add a logical statement, try not to modify the variables in the closure.

It seems that it is not possible to implement the function of the counter in the usual way, because the internal count +=1 the error before the assignment, and the workaround: (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:  print count () # 1,2,3,4,5,6,7,8,9,10count = Counter (0) print count () # 1

Because the list has variability, the string is immutable.

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

For example: If you need to define a local variable within function 1, the name of the other function 2 is the same, but also in function 1 to refer to the function 2.

def var ():  passdef F2 ():  var = ' Just a String '  f1 = Globals () [' var ']  print var  return type (F1) print F 2 () # Just a string# <type ' function ' >

Locals ()
If you have used a Python web framework, you have experienced the need to pass a lot of local variables in a view function to the template engine, and then work on the HTML. While you can have some more clever practices, you still want to pass a lot of variables at once. You don't have to know how these grammars come about, what you do, you just need to get a general idea of what locals () is.
As you can see, locals () throws all the local variables together.

 @app. Route ('/') def view (): User = User.query.all () Article = Article.query.all () IP = request.en       Viron.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) #或者 return render_template (' index.html ', **locals ()) 
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.