Chapter 17. Scopes
ChapterÂ 16 introduced basic function definitions and calls. As we saw, Pythonâs core function model is simple to use, but even simple function examples quickly led us to questions about the meaning of variables in our code. This chapter moves on to present the details behind Pythonâs scopesâthe places where variables are defined and looked up. Like module files, scopes help prevent name clashes across your programâs code: names defined in one program unit donât interfere with names in another.
As weâll see, the place where a name is assigned in our code is crucial to determining what the name means. Weâll also find that scope usage can have a major impact on program maintenance effort; overuse of globals, for example, is a generally bad thing. On the plus side, weâll learn that scopes can provide a way to retain state information between function calls, and offer an alternative to classes in some roles.
Python Scope Basics
Now that youâre ready to start writing 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: that is, the location of a nameâs assignment in your source code determines the scope of the nameâs visibility to your code.
Just about everything related to ...
Get Learning Python, 5th 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.