Tom Tom - 1 year ago 97
Python Question

How can I make a deepcopy of a function in Python?

I would like to make a deepcopy of a function in Python. The copy module is not helpful, according to the documentation, which says:

This module does not copy types like module, method, stack trace, stack frame, file,
socket, window, array, or any similar types. It does “copy” functions and classes (shallow
and deeply), by returning the original object unchanged; this is compatible with the way
these are treated by the pickle module.

My goal is to have two functions with the same implementation but with different docstrings.

def A():

B = make_a_deepcopy_of(A)
B.__doc__ = """B"""

So how can this be done?

Answer Source

The FunctionType constructor is used to make a deep copy of a function.

import types
def copy_func(f, name=None):
    return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
        f.func_defaults, f.func_closure)

def A():
B = copy_func(A, "B")
B.__doc__ = """B"""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download