Chapter 13. Scopes and Arguments

Chapter 12 looked at basic function definition and calls. As we’ve seen, the basic function model is simple to use in Python. This chapter presents the details behind Python’s scopes—the places where variables are defined, as well as argument passing—the way that objects are sent to functions as inputs.

Scope Rules

Now that you will begin to write your own functions, we need to get more formal about what names mean in Python. When you use a name in a program, Python creates, changes, or looks up the name in what is known as a namespace—a place where names live. When we talk about the search for a name’s value in relation to code, the term scope refers to a namespace—the location of a name’s assignment in your code determines the scope of the name’s visibility to your code.

Just about everything related to names happens at assignment in Python—even scope classification. As we’ve seen, names in Python spring into existence when they are first assigned a value, and must be assigned before they are used. Because names are not declared ahead of time, Python uses the location of the assignment of a name to associate it with (i.e., bind it to) a particular namespace. That is, the place where you assign a name determines the namespace it will live in, and hence its scope of visibility.

Besides packaging code, functions add an extra namespace layer to your programs—by default, all names assigned inside a function are associated with that function’s namespace, ...

Get Learning Python, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.