Make all variables in a Python function global

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}

Leave a Comment