1

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.

1
  • The best solution to your problem may involve not replacing the functions at all, or storing them in some sort of data structure rather than 15+ variables. Commented Aug 14, 2013 at 21:10

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.