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(): """A""" pass B = make_a_deepcopy_of(A) B.__doc__ = """B"""
So how can this be done?
Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In case of deep copy, a copy of object is copied in other object.
In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator.
You don't make a deep copy using list() . (Both list(...) and testList[:] are shallow copies.) You use copy.
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(): """A""" pass B = copy_func(A, "B") B.__doc__ = """B"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With