-2

How do you make a function do reverse of what it was programmed to do in Python without reprogramming the entire function? For example:

swap1 = "abc"
swap2 = "def"
def swap():
    global swap1, swap2
    swap1 = swap2

into

swap1 = "abc"
swap2 = "def"
def swap():
    global swap1, swap2
    swap2 = swap1

Any help is appreciated.

dimo414
  • 47,227
  • 18
  • 148
  • 244
hprogram
  • 61
  • 5

3 Answers3

5

A function can only do what it's designed to do. While some functions, by design, are reversible, there is no way to create a general case reverse function. Furthermore, many functions (notably hash functions) are intentionally designed to not be reversible, either simply because information is lost along the way, or because it is intentionally computationally impossible to reverse.

You would do better to rethink your design here - the pattern you demonstrated above using globals is highly undesirable, it will lead to very complex, difficult to maintain or understand code.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
3

in general there is no such way to do this. the computer cannot know what you mean by "reverse", since there are different ways of the "reverse of a function".

supinf
  • 302
  • 4
  • 13
2

No way to 'reverse' a function. Only rewriting it is possible. Sorry.

user3576467
  • 424
  • 1
  • 7
  • 10