Warning: Don't try this at home, you might burn it down.

There is no legitimate reason to do the following in the course of normal day-to-day programming. Please review the other answers to this question for more realistic alternatives.

I can barely imagine why you would want to do this, but here is a way to do it:

def f(a, b, c):
    d = 123
    e = 'crazy, but possible'
    globals().update(locals())

def g():
    print a, b, c, d ,e

>>> globals()
{'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
NameError: global name 'a' is not defined

>>> f(10, 20, 'blah')
>>> g()
10 20 blah 123 crazy, but possible

>>> globals()
{'a': 10, 'c': 'blah', 'b': 20, 'e': 'crazy, but possible', 'd': 123, 'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
Answer from mhawke on Stack Overflow
🌐
Finxter
blog.finxter.com › python-return-all-variables-from-function
Python Return All Variables From Function – Be on the Right Side of Change
Python functions can return multiple values, making it simpler than in other programming languages. We will explore three common methods of returning multiple variables from a function: using tuples, using lists, and using dictionaries.
🌐
Real Python
realpython.com › python-return-statement
The Python return Statement: Usage and Best Practices – Real Python
June 14, 2024 - This can be any data type, such as a number, string, list, or object. To return multiple values, list them after the return keyword separated by commas. Python packs these values into a tuple.
Top answer
1 of 5
71

Warning: Don't try this at home, you might burn it down.

There is no legitimate reason to do the following in the course of normal day-to-day programming. Please review the other answers to this question for more realistic alternatives.

I can barely imagine why you would want to do this, but here is a way to do it:

def f(a, b, c):
    d = 123
    e = 'crazy, but possible'
    globals().update(locals())

def g():
    print a, b, c, d ,e

>>> globals()
{'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
NameError: global name 'a' is not defined

>>> f(10, 20, 'blah')
>>> g()
10 20 blah 123 crazy, but possible

>>> globals()
{'a': 10, 'c': 'blah', 'b': 20, 'e': 'crazy, but possible', 'd': 123, 'g': <function g at 0x875230>, 'f': <function f at 0x8751b8>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
2 of 5
14

The pythonic way to do this is either to keep the variables in local scope (i.e. define them within each function) and pass them between the functions as arguments / return values; or to keep your variables as attributes of an object or class making your "functions" methods in that class. Either way is OK, but the global keyword is designed specifically to put you off using it in the way you describe. Global variables are not just "bad style" but they make your code very difficult to maintain, as any invariants that your variables need to stick to need to be checked in every function.

Here is an example of good style (with functions):

def quads(a, b, c):
    x1 = (-1.0 * b + math.sqrt(b * b - 4.0 * a * c)) / (2.0 * a)
    x2 = (-1.0 * b - math.sqrt(b * b - 4.0 * a * c)) / (2.0 * a)
    return x1, x2

def pretty(a, b, c, x1, x2):
    eqn = "%fx^2 + %fx + %c" % (a, b, c)
    print "The first solution to the equation %s is: %f" % (eqn, x1)
    print "The second solution to the equation %s is: %f" % (eqn, x2)
    return

def main():
    a = 100
    b = 200
    c = 300
    x1, x2 = quads(a, b, c)
    pretty(a, b, c, x1, x2)
    return

if __name__ == '__main__':
    main()

Here is an example of good style (with OOP):

class Quadratic(object):

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.x1 = None 
        self.x2 = None 
        self.solve() # Set x1 and x2 to correct values
        # To maintain the invariant between a, b, c and x1, x1
        # we should override __setattr__ or use descriptors or
        # properties so that self.solve() is called every time
        # a, b, or c are updated.
        return

    def solve(self):
        self.x1 = (-1.0 * self.b +
                   math.sqrt(self.b * self.b - 4.0 * self.a * self.c)) / (2.0 * self.a)
        self.x2 = (-1.0 * self.b - 
                   math.sqrt(self.b * self.b - 4.0 * self.a * self.c)) / 2.0 * self.a
        return 

    def pretty(self):
        eqn = "%fx^2 + %fx + %c" % (self.a, self.b, self.c)
        print "The first solution to the equation %s is: %f" % (eqn, self.x1)
        print "The second solution to the equation %s is: %f" % (eqn, self.x2)
        return

def main():
    quad = Quadratic(100, 200, 300)
    quad.pretty()
    return

if __name__ == '__main__':
    main()
🌐
datagy
datagy.io › home › python posts › python: return multiple values from a function
Python: Return Multiple Values from a Function • datagy
December 19, 2022 - One of the big differences between Python sets and lists is that lists are mutable in Python, meaning that they can be changed. If this is an important characteristic of the values you return, then this is a good way to go. Let’s see how we can return multiple values from a function, using both assignment to a single variable and to multiple variables. # Returning Multiple Values to Lists def return_multiple(): return [1, 2, 3] # Return all at once return_all = return_multiple() # Return multiple variables a, b, c = return_multiple() print(f'{return_all=}') print(f'{a=}') print(f'{b=}') print(f'{c=}') # Returns: # return_all=[1, 2, 3] # a=1 # b=2 # c=3
🌐
GameDev.net
gamedev.net › forums › topic › 402593-python-how-do-you-return-multiple-variables-from-a-function
Python: How do you return multiple variables from a function - For Beginners - GameDev.net
September 24, 2005 - The len(act) < 0 test is also broken and needs to be fixed (maybe len(act) == 0?). I would strongly recommend changing the code so that it does not rely on act being global--use of global variables makes code very fragile. Cancel Save · Splinter of Chaos · Author · 239 · July 09, 2006 11:03 AM · Okay . . . but then how do I use act then? I have about three (thus far) different functions that all require the use of act, do you sugest I call get_input() for each one? And lastly, what is the rsplit()? I do have Python 2.4, do I use it or don't? EDIT: The Python documentation said · Quote: rsplit( [sep [,maxsplit]]) Return a list of the words in the string, using sep as the delimiter string.
🌐
Python Basics
pythonbasics.org › multiple-return
Multiple return - Python Tutorial
But what if you have multiple variables in a function that you want access to? Create a function getPerson(). As you already know a function can return a single variable, but it can also return multiple variables. We’ll store all of these variables directly from the function call.
🌐
Stack Overflow
stackoverflow.com › questions › 57347703 › how-to-return-all-of-elements-from-function
python - How to return all of elements from function? - Stack Overflow
import json json_list = {"batfish_result": [ { "Action": { "0": "DENY" }, "Line_Content": { "0": "no-match" } }, { "Action": { "0": "PERMIT" }, "Line_Content": { "0": "permit 10.20.0.0 255.255.255.0" } } ] } def main(json_list): PASS = 'PASS' FAIL = 'FAIL' result = {} result_list = [] action_num_list = [] condition_list = ['permit', 'permit'] jsons = json_list["batfish_result"] for j in jsons: print(j) action = j['Action'] action_num = action["0"] action_num_list.append(action_num) for con in condition_list: for action in action_num_list: if action == con.upper(): result_list.append(PASS) result['msg'] = result_list else: result_list.append(FAIL) result['msg'] = result_list return result main(json_list) ... It should be comparing each action with each condition variable like this.
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Return Multiple Values from a Function in Python | note.nkmk.me
April 23, 2025 - You can unpack multiple return values and assign them to separate variables. ... The same applies to three or more return values. def test2(): return 'abc', 100, [0, 1, 2] a, b, c = test2() print(a) # abc print(b) # 100 print(c) # [0, 1, 2] ... By using [], you can return a list instead of a tuple. def test_list(): return ['abc', 100] result = test_list() print(result) print(type(result)) # ['abc', 100] # <class 'list'> ... Draw circle, rectangle, line, etc. with Python, Pillow
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › viewing-all-defined-variables-in-python
Viewing all defined variables in Python - GeeksforGeeks
December 11, 2020 - var2 = "Welcome to geeksforgeeks" var3 = {"1": "a", "2": "b"} var4 = 25 var5 = [1, 2, 3, 4, 5] var6 = (58, 59) # Store all the local variables in a list, # using locals keyword. locals_stored = set(locals()) # Iterate over the list and print the local # variables. print("Printing Local Variables") for name in locals_stored: val = eval(name) print(name, "is", type(val), "and is equal to ", val) # Store the global variables in a list using # globals keyword and subtract the previously # created list of built-in global variables from it. globals_stored = set(globals())-not_my_data # Print the glo
🌐
Python Tips
book.pythontips.com › en › latest › global_&_return.html
8. Global & Return — Python Tips 0.1 documentation
It is so # because the result variable is only accessible inside # the function in which it is created if it is not global. Traceback (most recent call last): File "", line 1, in result NameError: name 'result' is not defined # Now lets run the same code but after making the result # variable global def add(value1, value2): global result result = value1 + value2 add(2, 4) result 6 · So hopefully there are no errors in the second run as expected.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-return-statement
Python return statement | DigitalOcean
August 3, 2022 - This is similar to Currying, which is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is {cuboid_volume}') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is {cuboid_volume}')
🌐
Python
docs.python.org › 3 › faq › programming.html
Programming FAQ — Python 3.14.3 documentation
At the end of the loop, the value of x is 4, so all the functions now return 4**2, i.e. 16. You can also verify this by changing the value of x and see how the results of the lambdas change: ... In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global x:
Top answer
1 of 4
47

You can use the return statement to return a value from a function, this does not make it so that the returned variable (value) becomes available in the scope of the caller. To use the value in the caller you can either use it directly in a statement or capture the value in a variable.

Here's some code to demonstrate this:

def foo():
    x = 'hello world'
    return x  # return 'hello world' would do, too

foo()
print(x)   # NameError - x is not defined outside the function

y = foo()
print(y)   # this works

x = foo()
print(x)   # this also works, and it's a completely different x than that inside
           # foo()

z = bar(x) # of course, now you can use x as you want

z = bar(foo()) # but you don't have to
2 of 4
10

Effectively, there are two ways: directly and indirectly.

The direct way is to return a value from the function, as you tried, and let the calling code use that value. This is normally what you want. The natural, simple, direct, explicit way to get information back from a function is to return it. Broadly speaking, the purpose of a function is to compute a value, and return signifies "this is the value we computed; we are done here".

Directly using return

The main trick here is that return returns a value, not a variable. So return x does not enable the calling code to use x after calling the function, and does not modify any existing value that x had in the context of the call. (That's presumably why you got a NameError.)

After we use return in the function:

def example():
    x = 'hello world'
    return x

we need to write the calling code to use the return value:

result = example()
print(result)

The other key point here is that a call to a function is an expression, so we can use it the same way that we use, say, the result of an addition. Just as we may say result = 'hello ' + 'world', we may say result = foo(). After that, result is our own, local name for that string, and we can do whatever we want with it.

We can use the same name, x, if we want. Or we can use a different name. The calling code doesn't have to know anything about how the function is written, or what names it uses for things.1

We can use the value directly to call another function: for example, print(foo()).2 We can return the value directly: simply return 'hello world', without assigning to x. (Again: we are returning a value, not a variable.)

The function can only return once each time it is called. return terminates the function - again, we just determined the result of the calculation, so there is no reason to calculate any further. If we want to return multiple pieces of information, therefore, we will need to come up with a single object (in Python, "value" and "object" are effectively synonyms; this doesn't work out so well for some other languages.)

We can make a tuple right on the return line; or we can use a dictionary, a namedtuple (Python 2.6+), a types.simpleNamespace (Python 3.3+), a dataclass (Python 3.7+), or some other class (perhaps even one we write ourselves) to associate names with the values that are being returned; or we can accumulate values from a loop in a list; etc. etc. The possibilities are endless..

On the other hand, the function returns whether you like it or not (unless an exception is raised). If it reaches the end, it will implicitly return the special value None. You may or may not want to do it explicitly instead.


Indirect methods

Other than returning the result back to the caller directly, we can communicate it by modifying some existing object that the caller knows about. There are many ways to do that, but they're all variations on that same theme.

If you want the code to communicate information back this way, please just let it return None - don't also use the return value for something meaningful. That's how the built-in functionality works.

In order to modify that object, the called function also has to know about it, of course. That means, having a name for the object that can be looked up in a current scope. So, let's go through those in order:

Local scope: Modifying a passed-in argument

If one of our parameters is mutable, we can just mutate it, and rely on the caller to examine the change. This is usually not a great idea, because it can be hard to reason about the code. It looks like:

def called(mutable):
    mutable.append('world')

def caller():
    my_value = ['hello'] # a list with just that string
    called(my_value)
    # now it contains both strings

If the value is an instance of our own class, we could also assign to an attribute:

class Test:
    def __init__(self, value):
        self.value = value

def called(mutable):
    mutable.value = 'world'

def caller():
    test = Test('hello')
    called(test)
    # now test.value has changed

Assigning to an attribute does not work for built-in types, including object; and it might not work for some classes that explicitly prevent you from doing it.

Local scope: Modifying self, in a method

We already have an example of this above: setting self.value in the Test.__init__ code. This is a special case of modifying a passed-in argument; but it's part of how classes work in Python, and something we're expected to do. Normally, when we do this, the calling won't actually check for changes to self - it will just use the modified object in the next step of the logic. That's what makes it appropriate to write code this way: we're still presenting an interface, so the caller doesn't have to worry about the details.

class Example:
    def __init__(self):
        self._words = ['hello']
    def add_word(self):
        self._words.append('world')
    def display(self):
        print(*self.words)

x = Example()
x.add_word()
x.display()

In the example, calling add_word gave information back to the top-level code - but instead of looking for it, we just go ahead and call display.3

See also: Passing variables between methods in Python?

Enclosing scope

This is a rare special case when using nested functions. There isn't a lot to say here - it works the same way as with the global scope, just using the nonlocal keyword rather than global.4

Global scope: Modifying a global

Generally speaking, it is a bad idea to change anything in the global scope after setting it up in the first place. It makes code harder to reason about, because anything that uses that global (aside from whatever was responsible for the change) now has a "hidden" source of input.

If you still want to do it, the syntax is straightforward:

words = ['hello']
def add_global_word():
    words.append('world')

add_global_word() # `words` is changed

Global scope: Assigning to a new or existing global

This is actually a special case of modifying a global. I don't mean that assignment is a kind of modification (it isn't). I mean that when you assign a global name, Python automatically updates a dict that represents the global namespace. You can get that dict with globals(), and you can modify that dict and it will actually impact what global variables exist. (I.e., the return from globals() is the dictionary itself, not a copy.)5

But please don't. That's even worse of an idea than the previous one. If you really need to get the result from your function by assigning to a global variable, use the global keyword to tell Python that the name should be looked up in the global scope:

words = ['hello']

def replace_global_words():
    global words
    words = ['hello', 'world']

replace_global_words() # `words` is a new list with both words

Global scope: Assigning to or modifying an attribute of the function itself

This is a rare special case, but now that you've seen the other examples, the theory should be clear. In Python, functions are mutable (i.e. you can set attributes on them); and if we define a function at top level, it's in the global namespace. So this is really just modifying a global:

def set_own_words():
    set_own_words.words = ['hello', 'world']

set_own_words()
print(*set_own_words.words)

We shouldn't really use this to send information to the caller. It has all the usual problems with globals, and it's even harder to understand. But it can be useful to set a function's attributes from within the function, in order for the function to remember something in between calls. (It's similar to how methods remember things in between calls by modifying self.) The functools standard library does this, for example in the cache implementation.

Builtin scope

This doesn't work. The builtin namespace doesn't contain any mutable objects, and you can't assign new builtin names (they'll go into the global namespace instead).


Some approaches that don't work in Python

Just calculating something before the function ends

In some other programming languages, there is some kind of hidden variable that automatically picks up the result of the last calculation, every time something is calculated; and if you reach the end of a function without returning anything, it gets returned. That doesn't work in Python. If you reach the end without returning anything, your function returns None.

Assigning to the function's name

In some other programming languages, you are allowed (or expected) to assign to a variable with the same name as the function; and at the end of the function, that value is returned. That still doesn't work in Python. If you reach the end without returning anything, your function still returns None.

def broken():
    broken = 1

broken()
print(broken + 1) # causes a `TypeError`

It might seem like you can at least use the value that way, if you use the global keyword:

def subtly_broken():
    global subtly_broken
    subtly_broken = 1

subtly_broken()
print(subtly_broken + 1) # 2

But this, of course, is just a special case of assigning to a global. And there's a big problem with it - the same name can't refer to two things at once. By doing this, the function replaced its own name. So it will fail next time:

def subtly_broken():
    global subtly_broken
    subtly_broken = 1

subtly_broken()
subtly_broken() # causes a `TypeError`

Assigning to a parameter

Sometimes people expect to be able to assign to one of the function's parameters, and have it affect a variable that was used for the corresponding argument. However, this does not work:

def broken(words):
    words = ['hello', 'world']

data = ['hello']
broken(data) # `data` does not change

Just like how Python returns values, not variables, it also passes values, not variables. words is a local name; by definition the calling code doesn't know anything about that namespace.

One of the working methods that we saw is to modify the passed-in list. That works because if the list itself changes, then it changes - it doesn't matter what name is used for it, or what part of the code uses that name. However, assigning a new list to words does not cause the existing list to change. It just makes words start being a name for a different list.

For more information, see How do I pass a variable by reference?.


1 At least, not for getting the value back. If you want to use keyword arguments, you need to know what the keyword names are. But generally, the point of functions is that they're an abstraction; you only need to know about their interface, and you don't need to think about what they're doing internally.

2 In 2.x, print is a statement rather than a function, so this doesn't make an example of calling another function directly. However, print foo() still works with 2.x's print statement, and so does print(foo()) (in this case, the extra parentheses are just ordinary grouping parentheses). Aside from that, 2.7 (the last 2.x version) has been unsupported since the beginning of 2020 - which was nearly a 5 year extension of the normal schedule. But then, this question was originally asked in 2010.

3Again: if the purpose of a method is to update the object, don't also return a value. Some people like to return self so that you can "chain" method calls; but in Python this is considered poor style. If you want that kind of "fluent" interface, then instead of writing methods that update self, write methods that create a new, modified instance of the class.

4 Except, of course, that if we're modifying a value rather than assigning, we don't need either keyword.

5 There's also a locals() that gives you a dict of local variables. However, this cannot be used to make new local variables - the behaviour is undefined in 2.x, and in 3.x the dict is created on the fly and assigning to it has no effect. Some of Python's optimizations depend on the local variables for a function being known ahead of time.

🌐
Vultr
docs.vultr.com › python › examples › return-multiple-values-from-a-function
Python Program to Return Multiple Values From a Function | Vultr Docs
December 31, 2024 - This function get_stats calculates the minimum, maximum, and average of a list of numbers. It returns these three values enclosed in a tuple. When called, the results can be immediately unpacked into three variables which can then be used independently.
🌐
Flexiple
flexiple.com › python › python-return-multiple-values
Return multiple values from a function in Python | Flexiple Tutorials - Flexiple
#Returning Multiple Values using Tuples def multiple(): operation = "Sum" total = 5+10 return operation, total; operation, total = multiple() print(operation, total) #Output = Sum 15 · A common confusion here is that the syntax of tuple requires a pair of brackets (). Although this is true, Python does not always require brackets to identify a tuple.
🌐
W3Schools
w3schools.com › python › gloss_python_function_return_value.asp
Python Function Return Value
Python Functions Tutorial Function Call a Function Function Arguments *args Keyword Arguments **kwargs Default Parameter Value Passing a List as an Argument Function Return Value The pass Statement i Functions Function Recursion ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
🌐
Nanyang Technological University
libguides.ntu.edu.sg › python › functionreturn
2.3 Functions with Return Values - Python for Basic Data Analysis - LibGuides at Nanyang Technological University
Start your data science journey with Python. Learn practical Python programming skills for basic data manipulation and analysis. ... Using return, you can write a function that returns a value. You can assign the returned values to a variable which can be used in whatever manner you choose.
🌐
Gurobi
support.gurobi.com › hc › en-us › community › posts › 27812151685137-Passing-multiple-variables-across-Python-function-methods
Passing multiple variables across Python function/methods – Gurobi Help Center
I wonder if I can pass multiple/all variables across Python functions considering many variables to pass on so that they are accessible and optimized outside the function. For example: def vars_constrs(m): # Create vars and constraints a = m.addVars(range(10)) b = m.addVars(range(10)) ...... z = m.addVars(range(10)) (Create some constraints here) ...... return All_variables # Main program m = gp.Model('all') All_variables = vars_constrs(m) ( Unpack_all_variables(All_variables) ) m.optimize() # Accessing all variable values val_a = [a[i].X for i in range(10)] ...