[Python-Dev] Fixing copy.py to allow copying functions

Guido van Rossum guido at python.org
Wed Feb 22 02:22:20 CET 2006

While playing around with the defaultdict patch, adding __reduce__ to
make defaultdict objects properly copyable through the copy module, I
noticed that copy.py doesn't support copying function objects. This
seems an oversight, since the (closely related) pickle module *does*
support copying functions. The semantics of pickling a function is
that it just stores the module and function name in the pickle; that
is, if you unpickle it in the same process it'll just return a
reference to the same function object. This would translate into
"atomic" semantics for copying functions: the "copy" is just the
original, for shallow as well as deep copies. It's a simple patch:

--- Lib/copy.py (revision 42537)
+++ Lib/copy.py (working copy)
@@ -101,7 +101,8 @@
     return x
 for t in (type(None), int, long, float, bool, str, tuple,
           frozenset, type, xrange, types.ClassType,
-          types.BuiltinFunctionType):
+          types.BuiltinFunctionType,
+         types.FunctionType):
     d[t] = _copy_immutable
 for name in ("ComplexType", "UnicodeType", "CodeType"):
     t = getattr(types, name, None)
@@ -217,6 +218,7 @@
 d[xrange] = _deepcopy_atomic
 d[types.ClassType] = _deepcopy_atomic
 d[types.BuiltinFunctionType] = _deepcopy_atomic
+d[types.FunctionType] = _deepcopy_atomic

 def _deepcopy_list(x, memo):
     y = []

Any objections? Given that these are picklable, I can't imagine there
are any but I thought I'd ask anyway.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list