Program Scope and How to Handle It

Introduction

This topic refers to more advanced programs, where most code is contained in functions.

Python Scope and Scope Errors

In programming, "scope" refers to the section of code that is currently executing. For example, when a function is called, only the code within that function is executing. When a variable is defined in a function, it ONLY exists within that scope and when that function is executing ; otherwise it does not exist.

Take the code sample below. There is one global variable. (Global variables should normally be read-only. And their use should be minimized.)

Other variables (order_total, tax) are defined within functions, as they should be. But when order_total is declared in functionA, it does not exist in functionB. Any statement outside of functionA that refers to order_total will throw an error. It does not matter that the variable name is the same or correct - if the variable is "out of scope"; it is an undeclared variable. The same is true for the tax variable, which is declared in functionB.

Example of Scope Issues

Figure 1: Example of Scope Issues

How to Handle Scope

The example below is coded correctly to handle these scope issues. Variables should normally be declared where they are used, as done here.

The way to handle scope issues is to return values from functions, and then submit values when calling functions. The code example below handles this in the proper manner.

Example of Handling Scope Issues

Figure 2: Example of Handling Scope Issues

Note that the variable names do not need to be the same when returned from a function and when submitted to a function. In fact, it is often better NOT to use the same names, so there is less confusion. When a value is submitted to a function, it is the "value" that is submitted - not the variable.

In the example above, when functionA returns its value, it is assigned to a new variable named total. The value of total is then submitted to functionB (where it is renamed for that function).

Functions "rename" parameter values. functionB declares the incoming value as a variable named new_total. Inside of functionB, the variable that exists is named new_total.

The return statement of functionB returns the value of its internal variable named tax, not the variable itself. The variable itself is destroyed and does not exist after that statement.

Caution: do NOT try to declare all variables as Global variables to avoid scope issues!

Global variables should normally be read-only, unchangeable variables. There are cases where updateable global variables are proper and practical, and those cases will be pointed out.