GDICommander
GDICommander

Reputation: 1333

How to reset some function variables in Python in a loop

I have a script where I have to change some functions and reset the changes I made to them. I currently do it like this:

def a():
    pass

def b():
    pass

def c():
    pass

def d():
    pass

previous_a = a
previous_b = b
previous_c = c

a = d
b = d
c = d

# I want to make the following code block shorter.
a = previous_a
b = previous_b
c = previous_c

Instead of enumerating all the functions to reset, I would like to have a loop that iterates on a data structure (a dictionary, perhaps) and resets the function variables with their previous values. In the previous example, the current approach 3 functions is ok, but doing that for 15+ functions will produce a big code chunk that I would like to reduce.

Unfortunately, I have been unable to find a viable solution. I thought of weakrefs, but my experiments with them failed.

Upvotes: 1

Views: 836

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

Just store the old functions in a dictionary:

old = {'a': a, 'b': b, 'c': c}

then use the globals() dictionary to restore them:

globals().update(old)

This only works if a, b and c were globals to begin with.

You can use the same trick to assign d to all those names:

globals().update(dict.fromkeys(old.keys(), d))

This sets the keys a, b and c to the same value d.

Upvotes: 5

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

Function definitions are stored in the "global" scope of the module where they are declared. The global scope is a dictionary. As such, you could access/modify its values by key.

See this example:

>>> def a():
...   print "a"
... 
>>> def b():
...   print "b"
... 
>>> def x():
...   print "x"
... 
>>> for i in ('a', 'b'):
...   globals()[i] = x
... 
>>> a()
x

Upvotes: 0

Related Questions