bpo-38293: Allow shallow and deep copying of property objects (GH-16438)

Copying property objects results in a TypeError. Steps to reproduce:

```
>>> import copy
>>> obj = property()
>>> copy.copy(obj)
````

This affects both shallow and deep copying.  
My idea for a fix is to add property objects to the list of "atomic" objects in the copy module.
These already include types like functions and type objects.

I also added property objects to the unit tests test_copy_atomic and test_deepcopy_atomic. This is my first PR, and it's highly likely I've made some mistake, so please be kind :)


https://bugs.python.org/issue38293
This commit is contained in:
Guðni Natan Gunnarsson 2020-01-12 17:41:49 +00:00 committed by Miss Islington (bot)
parent 54cfbb2fee
commit 9f3fc6c5b4
3 changed files with 5 additions and 3 deletions

View File

@ -107,7 +107,7 @@ _copy_dispatch = d = {}
def _copy_immutable(x):
return x
for t in (type(None), int, float, bool, complex, str, tuple,
bytes, frozenset, type, range, slice,
bytes, frozenset, type, range, slice, property,
types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
@ -195,6 +195,7 @@ d[type] = _deepcopy_atomic
d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic
d[weakref.ref] = _deepcopy_atomic
d[property] = _deepcopy_atomic
def _deepcopy_list(x, memo, deepcopy=deepcopy):
y = []

View File

@ -99,7 +99,7 @@ class TestCopy(unittest.TestCase):
42, 2**100, 3.14, True, False, 1j,
"hello", "hello\u1234", f.__code__,
b"world", bytes(range(256)), range(10), slice(1, 10, 2),
NewStyle, Classic, max, WithMetaclass]
NewStyle, Classic, max, WithMetaclass, property()]
for x in tests:
self.assertIs(copy.copy(x), x)
@ -357,7 +357,7 @@ class TestCopy(unittest.TestCase):
pass
tests = [None, 42, 2**100, 3.14, True, False, 1j,
"hello", "hello\u1234", f.__code__,
NewStyle, Classic, max]
NewStyle, Classic, max, property()]
for x in tests:
self.assertIs(copy.deepcopy(x), x)

View File

@ -0,0 +1 @@
Add :func:`copy.copy` and :func:`copy.deepcopy` support to :func:`property` objects.