Python learning 05.08: Python variable scope

The so-called Scope is the effective range of a variable, which range a variable can be used in. Some variables can be used anywhere in the whole code, some variables can only be used inside the function, some variables can only be used inside the for loop.

The scope of variable is determined by the definition position of variable. The scope of variable defined in different positions is different. In this section, we will only cover two kinds of variables, local variables and global variables.

Python local variable

The scope of a variable defined within a function is also limited to the function itself, and it can't be used outside of a function. We call such a variable Local Variable.

You know, when a function is executed, Python allocates a temporary storage space for it, in which all variables defined inside the function are stored. After the function is executed, the temporary storage space will be released and recycled, and the variables stored in the space will no longer be used.

for instance:

def demo():
    add = "http://c.biancheng.net/python/"
    print("Internal function add =",add)

   
demo()
print("External function add =",add)

# The execution result of the program is:

//Function internal add = http://c.biancheng.net/python/
Traceback (most recent call last):
  File "C:\Users\mengma\Desktop\file.py", line 6, in <module>
    print("External function add =",add)
NameError: name 'add' is not defined

You can see that if you try to access the variables defined inside the function, the Python interpreter will report a NameError and prompt us that we have not defined the variables to access. This also confirms that when the function is executed, the variables defined inside the function will be destroyed and recycled.

It is worth mentioning that the parameters of a function are also local variables and can only be used inside a function. For example:

def demo(name,add):
    print("Internal function name =",name)
    print("Internal function add =",add)
demo("Python Course","http://c.biancheng.net/python/")

print("External function name =",name)
print("External function add =",add)


# The execution result of the program is: 

//Function internal name = Python tutorial
//Function internal add = http://c.biancheng.net/python/
Traceback (most recent call last):
  File "C:\Users\mengma\Desktop\file.py", line 7, in <module>
    print("External function name =",name)
NameError: name 'name' is not defined

 

Since the Python interpreter runs the program code line by line, I'm only prompted here that "name has no definition". In fact, accessing the add variable outside the function will report the same error.

Python global variables

In addition to defining variables inside functions, Python allows variables to be defined outside all functions. Such variables are called global variables.

Different from local variables, the default scope of global variables is the entire program, that is, global variables can be used either outside or inside each function.

There are two ways to define global variables:

  • The variables defined outside the function must be global variables, such as:
    add = "http://c.biancheng.net/shell/"
    def text():
        print("Function body access:",add)
    text()
    print('Function external access:',add)
    
    
    # The operation result is:
    
    //Function body access: http://c.biancheng.net/shell/
    //Function external access: http://c.biancheng.net/shell/

    Define global variables in the function body. That is, after using the global keyword to modify the variable, the variable will become a global variable. For example:

def text():
    global add
    add= "http://c.biancheng.net/java/"
    print("Function body access:",add)
text()
print('Function external access:',add)


# The operation results are as follows:

//Function body access: http://c.biancheng.net/java/
//Function external access: http://c.biancheng.net/java/

Note that when using the global keyword to modify the variable name, you cannot directly assign the initial value to the variable, otherwise a syntax error will be caused.

Gets the variable in the specified scope

In some specific scenarios, we may need to get all variables in a certain scope (global or local). Python provides the following three ways:

1) globals() function

The globals() function is Python's built-in function. It can return a dictionary containing all variables in the global scope. Each key value pair in the dictionary is the variable name and the value is the value of the variable.

for instance:

#global variable
Pyname = "Python Course"
Pyadd = "http://c.biancheng.net/python/"
def text():
    #local variable
    Shename = "shell Course"
    Sheadd= "http://c.biancheng.net/shell/"
print(globals())


# The execution result is:

{ ...... , 'Pyname': 'Python Course', 'Pyadd': 'http://c.biancheng.net/python/', ......}

Note that the dictionary returned by the globals() function will contain many variables by default, which are built-in to the Python main program, and the reader will ignore them for the moment.

As you can see, by calling the globals() function, we can get a dictionary containing all global variables. Moreover, through this dictionary, we can also access the specified variable, and even modify its value if necessary. For example, based on the above program, add the following statement:

print(globals()['Pyname'])
globals()['Pyname'] = "Python Introductory course"
print(Pyname)


# The execution result is:
 
Python Course
Python Introductory course

 

2) locals() function

The locals() function is also one of Python's built-in functions. By calling this function, we can get a dictionary containing all variables in the current scope. The so-called "current scope" here refers to that if you call the locals() function within the function, you will get a dictionary containing all local variables; if you call the locals() function within the global template, its function is the same as that of the global() function.

for instance:

#global variable
Pyname = "Python Course"
Pyadd = "http://c.biancheng.net/python/"
def text():
    #local variable
    Shename = "shell Course"
    Sheadd= "http://c.biancheng.net/shell/"
    print("Function internal locals:")
    print(locals())
text()
print("External to function locals:")
print(locals())

# The execution result is:
 
//The locales inside the function:
{'Sheadd': 'http://c. Biancheng. Net / shell / ','shename':'shell tutorial '}
//Locales outside the function:
{...... , 'Pyname': 'Python Course', 'Pyadd': 'http://c.biancheng.net/python/', ...... }

When using the locals() function to get all global variables, like the globals() function, the dictionary returned by it will contain many variables by default, which are built-in in Python main program, and readers will ignore them for the moment.
Note that when using the locals() function to get the dictionary of all local variables, you can access the corresponding variable value by specifying the key like the global() function, but you cannot modify the variable value. For example:

#global variable
Pyname = "Python Course"
Pyadd = "http://c.biancheng.net/python/"
def text():
    #local variable
    Shename = "shell Course"
    Sheadd= "http://c.biancheng.net/shell/"
    print(locals()['Shename'])
    locals()['Shename'] = "shell Introductory course"
    print(Shename)
text()


# The operation result is:

Python Course
Python Course

 

Obviously, the dictionary of local variables returned by locals() can be used to access variables, but the value of variables cannot be modified.

3) vars(object)

The vars() function is also a Python built-in function. Its function is to return a dictionary of all variables within the scope of the specified object object. If you don't pass in the object parameter, vars () and locals() have exactly the same function.

At present, the reader has not learned Python classes and objects, so beginners can skip the learning of this function first, and then turn back to learn this function after learning Python classes and objects.

for instance:

 #global variable
Pyname = "Python Course"
Pyadd = "http://c.biancheng.net/python/"
class Demo:
    name = "Python Course"
    add = "http://c.biancheng.net/python/"
print("Yes object: ")
print(vars(Demo))

print("nothing object: ")
print(vars())


# The operation result is:

//There are object s:
{...... , 'name': 'Python Course', 'add': 'http://c.biancheng.net/python/', ......}
//No object:
{...... , 'Pyname': 'Python Course', 'Pyadd': 'http://c.biancheng.net/python/', ...... }

Tags: Programming Python shell Java

Posted on Mon, 03 Feb 2020 07:35:53 -0800 by leeandrew