How to Return a Global and Local Variable from a Python Function?

5/5 - (2 votes)

πŸ’¬ Question: How to return a global variable from a Python function. And how to return a local variable?

First, have a look at the overview figure that shows how to return a local and global variable from a Python function using a simple example:

Let’s dive into this example in more detail and answer the question of how to return a local variable first. We’ll learn how to return a global variable from a function afterward by building on what we’ve learned. πŸ‘‡

Return a Local Variable From Function

If you assign a value to a variable inside a function scope, Python will create a new local variable. This new local variable will be created even if you have already defined the same variable outside the function scope.

🐍 Changing the local variable doesn’t change the global variable. The change is only visible inside the function scope. The local variable overshadows the global variable.

The following example shows how you can create and return a local variable x = 'alice' from a function that overshadows the global variable x = 42.

x = 42

def f():
    x = 'alice'
    return x

print(f())
# alice

# Has the global variable x changed?
print(x)
# Output: 42 - no it has not changed.

🌍 Recommended Tutorial: Python Namespaces Made Simple

Return a Global Variable From a Function

To return a global variable x from a Python function, add the line global x inside the function scope. Each time you read or write the variable inside the function after this line, you’ll read or write the global variable. To return the global variable then simply write return x.

The following code shows that changing the global variable inside the function has side effects, i.e., it can be seen from the outside in contrast to the previous example when changing the local variable x inside the function didn’t affect the global variable x.

x = 42

def f():
    global x
    x = 'alice'
    return x

print(f())
# alice

# Has the global variable x changed?
print(x)
# Output: alice - yes it has changed.

🌍 Recommended Tutorial: Python Aliasing Method Names

Example – Analyzing the Local and Global Scope

To check the local and global scope, i.e., which variables are defined locally and globally, you can use the dir() function like so:

x = 42

def f():
    
    print(dir())
    # []
    
    global x
    x = 'alice'
    
    print(dir())
    # []
    
    return x

print(dir())
# ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f', 'x']

print(f())
# alice

# Has the global variable x changed?
print(x)
# Output: alice - yes it has changed.

This shows that the local scope doesn’t change inside the function because Python works on the global variable.

Note that without the global x definition inside the function, the variable x would in fact be a local variable as can be seen in the highlighted area:

x = 42

def f():
    
    print(dir())
    # []
    
    x = 'alice'
    
    print(dir())
    # ['x']
    
    return x

print(dir())
# ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f', 'x']

print(f())
# alice

# Has the global variable x changed?
print(x)
# Output: alice - yes it has changed.

Okay, let’s close this tutorial with a short recap of the dir() function for learning and ease of understanding of the previous code snippet.

Python dir() Recap

Python dir() Visual Explanation

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scopeβ€”the namespace of your current module.

If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope.

Thus, dir() returns all names in a given scope.

🌍 Recommended Tutorial: Python dir() β€” A Simple Guide with Video

Summary

Per default, Python returns variables in the local scope, not in the global scope. To explicitly return a global variable x, use the line global x before changing or returning it from the function.

🌍 Recommended Tutorial: How to Use Global Variables In a Python Function?


Thanks for reading this tutorial! ❀️ Feel free to join my free email academy and download our Python cheat sheets for maximum learning efficiency (I’m German, so I care a lot about efficiency). πŸ˜‰