Scope

Published

2023-07-31

Scope

Names of formal parameters and any local variables created within a function have a limited lifetime—they exist only until the function is done with its work. We refer to this as scope.

The most important thing to understand here is that names of formal parameters and names of local variables we define within a function have local scope. They have a lifetime limited to the execution of the function, and then those names are gone.

Here’s a trivial example.

>>> def foo():
...     x = 1
...     return x
...

>>> y = foo()
>>> y
1

The name x within the function foo only exists as long as foo is being executed. Once foo returns the value of x, x is no more.

>>> def foo():
...     x = 1
...     return x
...

>>> y = foo()
>>> y
1
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

So the name x lives only within the execution of foo. In this example, the scope of x is limited to the function foo.

Shadowing

It is, perhaps, unfortunate that Python allows us to use variable names within a function that exist outside the function. This is called shadowing, and it sometimes leads to confusion.

Here’s an example:

>>> def square(x):
...    x = x * x
...    return x
...
>>> x = 5
>>> y = square(x)
>>> y
25
>>> x
5

What has happened? Didn’t we set x = x * x? Shouldn’t x also be 25?

No. Here we have two different variables with the same name, x. We have the x in the outer scope, created with the assignment x = 5. The x within the function square is local, within that function. Yes, it has the same name as the x in the outer scope, but it’s a different x.

Generally, it’s not a good idea to shadow variable names in a function. Python allows it, but this is more a matter of style and avoiding confusion. Oftentimes, we rename the variables in our functions, appending an underscore.

>>> def square(x_):
...    x_ = x_ * x_
...    return x_
...
>>> x = 5
>>> y = square(x)
>>> y
25

This is one way to avoid shadowing.

Another approach is to give longer, more descriptive names to variables in the outer scope, and leave the shorter or single-character names to the function. Which approach is best depends on context.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).