Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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():     """A"""     pass  B = make_a_deepcopy_of(A) B.__doc__ = """B""" 

So how can this be done?

like image 769
Tom Avatar asked Jun 29 '11 21:06

Tom


People also ask

How do you deep copy a function?

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.

How do you copy the value of a variable in Python?

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.

Does list () create a deep copy?

You don't make a deep copy using list() . (Both list(...) and testList[:] are shallow copies.) You use copy.


1 Answers

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""" 
like image 167
Glenn Maynard Avatar answered Sep 30 '22 15:09

Glenn Maynard