Please don't do this.
If your f() consists entirely of these function calls:
def f():
call_some_function_A()
call_some_function_B()
# [...]
call_some_function_Z()
...you can hack into it and get all the names it references:
names = f.__code__.co_names
# ('call_some_function_A', 'call_some_function_B', 'call_some_function_Z')
But you still need to get the corresponding functions.
If the functions are in some other module or anything similar, just do this:
functions = [getattr(some_module, name) for name in names]
If the functions are defined in the same file as globals, do this:
functions = [globals()[name] for name in names]
# [<function __main__.call_some_function_A>, <function __main__.call_some_function_B>, <function __main__.call_some_function_Z>]
Then all you need to do is call them in reverse order:
def f_():
for func in reversed(functions):
func()
Alternatively, you can obtain the function's source code, parse it, reverse the the abstract syntax tree, compile it back, execute it... and you will have yourself the reversed function.
Let's consider this example:
def f():
call_some_function_A()
if whatever:
call_some_function_B()
call_some_function_C()
call_some_function_D()
import inspect
import ast
original_f = f
source = inspect.getsource(f)
tree = ast.parse(source)
# tree is a Module, with body consisting of 1 FunctionDef
# tree.body[0] is a FunctionDef, with body consisting of Exprs
tree.body[0].body.reverse()
# top level expressions will be reversed
# compile the modified syntax tree to a code object as a module and execute it
exec(compile(tree, '<unknown>', 'exec'))
# f will be overwritten because the function name stays the same
# now f will be equivalent to:
# def f():
# call_some_function_D()
# if test:
# call_some_function_B()
# call_some_function_C()
# call_some_function_A()
f_ = f
f = original_f
So yes, this method is a bit better. It is even possible to recursively reverse all the bodys and achieve the reversal of ...B and ...C as well, but if even the simplest logic code is introduced, you will run into bad problems.