Reading: Scopes

In this section, we discuss the concept of scopes in Python, which defines the region of code where an identifier can be accessed or used.

Understanding scopes is essential for managing variable visibility and ensuring that code behaves as expected. Python provides several built-in methods, such as globals(), locals(), and dir(), to help developers check the scope of identifiers.

There are three main types of scopes in Python:

  1. Local Scope: This refers to identifiers declared within a specific function. Each function maintains its own local namespace, and variables defined within that function cannot be accessed outside of it.

  2. Global Scope: This encompasses all identifiers declared at the module level (the current file). Variables defined in the global scope can be accessed from any function within the module.

  3. Built-in Scope: This includes identifiers that are built into Python and available at all times, such as functions like range() and min(). These identifiers do not require any imports.

Python follows specific precedence rules when it comes to scopes. If an identifier is found in multiple scopes, the local scope takes precedence over the global scope, and the global scope takes precedence over the built-in scope.

For example, if a custom function named range is defined, it will be called in preference to Python's built-in range() function due to the local scope precedence.

To illustrate these concepts, we create a custom range function that multiplies its input by 123. When this function is called with the argument 12, it returns 1476, demonstrating that the local scope is utilized rather than the built-in range() function.

You have completed 0% of the lesson
0%