Make all variables in a Python function global

Viewed 29143

Is there a simple way to make all variables in a function global?

I have 20 odd variables in a function and naming them global one by one doesn't make nice code... to me anyway :)

5 Answers

A niche example where I wanted to do this: use a function for importing.*

def temp():
    a = "stays local value"
    old_locs = locals().copy()
    b = "is global value"
    import math
    new_locs = locals()
    new_vars = {k: new_locs[k] for k in set(new_locs) - set(old_locs)
                if k != 'old_locs'}
    globals().update(new_vars)    
temp()
print(b)
print(math.sqrt(3))
print(a)

gives
is global value

1.7320508075688772

NameError: name 'a' is not defined

This way only the specific 20 or so variables would get update the global namespace and intermediate variable names in the function wouldn't.

*I needed to import from a .ipynb file, and the process for doing so depends if called from google Collaboratory, a desktop .ipynb, or a desktop .py file; this involved the use of magics which are treated as invalid syntax in situation which wouldn't call those branches, so by importing my import function I can escape that issue.

Related