Back to Freecodecamp

What Is Scope in Python and How Does It Work?

curriculum/challenges/english/blocks/lecture-understanding-functions-and-scope/67fe85a1b634a335b18ae09a.md

latest5.5 KB
Original Source

--description--

In Python, scope determines the point at which you can access a variable. It's what controls the lifetime of a variable and how it is resolved in different parts of the code.

To correctly determine scope, Python follows the LEGB rule, which stands for the following:

  • Local scope (L): Variables defined in functions or classes.

  • Enclosing scope (E): Variables defined in enclosing or nested functions.

  • Global scope (G): Variables defined at the top level of the module or file.

  • Built-in scope (B): Reserved names in Python for predefined functions, modules, keywords, and objects.

Python uses the LEGB rule to resolve the scope of the variables in your program. We'll dive into each of these rules so you get a better understanding of the process.

Local scope means that a variable declared inside a function or class can only be accessed within that function or class.

Here's an example:

python
def my_func():
    my_var = 10
    print(my_var)

In this case, the my_func function has its own scope which cannot be accessed from outside the function. Calling my_func will output 10, but printing my_var outside the function will lead to a NameError:

python
def my_func():
    my_var = 10 # Locally scoped to my_func
    print(my_var)

my_func() # 10

print(my_var) # NameError: name 'my_var' is not defined

Enclosing scope means that a function that's nested inside another function can access the variables of the function it's nested within.

For example:

python
def outer_func():
    msg = 'Hello there!'

    def inner_func():
        print(msg)

    inner_func()

outer_func() # Hello there!

In this example, the inner function, inner_func, can freely access the msg variable defined in the outer function, outer_func. However, note that outer functions cannot access variables defined within any nested functions:

python
def outer_func():
    msg = 'Hello there!'
    print(res)

    def inner_func():
        res = 'How are you?'
        print(msg)

    inner_func()

outer_func() # NameError: name 'res' is not defined

That's because res is locally scoped to inner_func. Also, notice that outer_func tries to print res before inner_func is called.

One solution is to initialize res as an empty string in the enclosing scope, which is within outer_func. Then within inner_func, make res a non-local variable with the nonlocal keyword:

python
def outer_func():
    msg = 'Hello there!'
    res = ""  # Declare res in the enclosing scope

    def inner_func():
        nonlocal res  # Allow modification of an enclosing variable
        res = 'How are you?'
        print(msg)  # Accessing msg from outer_func()

    inner_func()
    print(res)  # Now res is accessible and modified

outer_func()

# Output:
# Hello there!
# How are you?

Global scope refers to variables that are declared outside any functions or classes which can be accessed from anywhere in the program. Here, my_var can be accessed anywhere, even inside a function it's not defined in:

python
my_var = 100

def show_var():
    print(my_var)

show_var() # 100
print(my_var) # 100

And if you want to make a locally scoped variable defined inside a function globally accessible, you can use the global keyword:

python
my_var_1 = 7

def show_vars():
    global my_var_2
    my_var_2 = 10
    print(my_var_1)
    print(my_var_2)

show_vars() # 7 10

# my_var_2 is now a global variable and can be accessed anywhere in the program
print(my_var_2) # 10

You can also use the global keyword to modify a global variable:

python
my_var = 10  # A global variable

def change_var():
    global my_var  # Allows modification of a global variable
    my_var = 20

change_var()

print(my_var)  # my_var is now modified globally to 20

Finally, built-in scope refers to all of Python's built-in functions, modules, and keywords, and are available anywhere in your program:

python
print(str(45)) # '45'
print(type(3.14)) # <class 'float'>
print(isinstance(3, str)) # False

--questions--

--text--

What is the rule Python follows to determine the scope of a variable?

--answers--

STACK: Static, Temporary, Active, Constant, Keyword

--feedback--

It consists of four levels, starting from the most specific to the most general.


TREE: Temporary, Reserved, Enclosing, External

--feedback--

It consists of four levels, starting from the most specific to the most general.


LEGB: Local, Enclosing, Global, Built-in


SCOPE: Script, Constant, Outer, Python, Embedded

--feedback--

It consists of four levels, starting from the most specific to the most general.

--video-solution--

3

--text--

What does the nonlocal keyword do?

--answers--

Makes a variable global.

--feedback--

It helps modify variables in an outer function.


Creates a new local variable.

--feedback--

It helps modify variables in an outer function.


Prevents variable reassignment.

--feedback--

It helps modify variables in an outer function.


Allows modifying a variable from an enclosing function

--video-solution--

4

--text--

Which keyword can you use to modify a global variable in Python?

--answers--

global


local

--feedback--

It allows changes to a variable outside the function.


static

--feedback--

It allows changes to a variable outside the function.


nonlocal

--feedback--

It allows changes to a variable outside the function.

--video-solution--

1