Here is a somewhat hacky way to do this, which first creates a new function from an existing one with a modification, and then replaces the source code with it. This is mainly because the types.CodeType() call has so many arguments. The Python 3 version (not shown) that I also implemented is slightly different from the fact that several function.func_code attributes got renamed, and the calling sequence types.CodeType() was slightly changed.
I got an idea from this answer from @aaronasterling (who said they got the idea from Michael Ford's Voidspace blog called Selfless Python ). It can be easily turned into a decorator, but I donβt see it useful, based on what you told us about the intended use.
import types def change_func_args(function, new_args): """ Create a new function with its arguments renamed to new_args. """ code_obj = function.func_code assert(0 <= len(new_args) <= code_obj.co_argcount) # the arguments are just the first co_argcount co_varnames # replace them with the new argument names in new_args new_varnames = tuple(list(new_args[:code_obj.co_argcount]) + list(code_obj.co_varnames[code_obj.co_argcount:])) # type help(types.CodeType) at the interpreter prompt for information new_code_obj = types.CodeType(code_obj.co_argcount, code_obj.co_nlocals, code_obj.co_stacksize, code_obj.co_flags, code_obj.co_code, code_obj.co_consts, code_obj.co_names, new_varnames, code_obj.co_filename, code_obj.co_name, code_obj.co_firstlineno, code_obj.co_lnotab, code_obj.co_freevars, code_obj.co_cellvars) modified = types.FunctionType(new_code_obj, function.func_globals) function.__code__ = modified.__code__ # replace code portion of original if __name__ == '__main__': import inspect def f(x, y): return x+y def g(a, b): return f(a, b) print('Before:') print('inspect.getargspec(g).args: {}'.format(inspect.getargspec(g).args)) print('g(1, 2): {}'.format(g(1, 2))) change_func_args(g, ['p', 'q']) print('') print('After:') print('inspect.getargspec(g).args: {}'.format(inspect.getargspec(g).args)) print('g(1, 2): {}'.format(g(1, 2)))
Output:
Before: inspect.getargspec(g).args: ['a', 'b'] g(1, 2): 3 After: inspect.getargspec(g).args: ['p', 'q'] g(1, 2): 3