[issue45167] deepcopy of GenericAlias with __deepcopy__ method is broken

Jacob Hayes report at bugs.python.org
Fri Sep 10 13:09:52 EDT 2021


New submission from Jacob Hayes <jacob.r.hayes at gmail.com>:

When deepcopying a parametrized types.GenericAlias (eg: a dict subclass) that has a __deepcopy__ method, the copy module doesn't detect the GenericAlias as a type and instead tries to call cls.__deepcopy__, passing `memo` inplace of self. This doesn't seem to happen with `typing.Generic` however.

Example:
```
from copy import deepcopy


class X(dict):
    def __deepcopy__(self, memo):
        return self


print(deepcopy(X()))
print(deepcopy(X))

print(type(X[str, int]))
print(deepcopy(X[str, int]()))
print(deepcopy(X[str, int]))
```
shows
```
{}
<class '__main__.X'>
<class 'types.GenericAlias'>
{}
Traceback (most recent call last):
  File "/tmp/demo.py", line 14, in <module>
    print(deepcopy(X[str, int]))
  File "/Users/jacobhayes/.pyenv/versions/3.9.6/lib/python3.9/copy.py", line 153, in deepcopy
    y = copier(memo)
TypeError: __deepcopy__() missing 1 required positional argument: 'memo'
```

I don't know if it's better to update `copy.deepcopy` here or perhaps narrow the `__getattr__` for `types.GenericAlias` (as `typing. _BaseGenericAlias` seems to).

----------
components: Library (Lib)
messages: 401601
nosy: JacobHayes
priority: normal
severity: normal
status: open
title: deepcopy of GenericAlias with __deepcopy__ method is broken
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45167>
_______________________________________


More information about the Python-bugs-list mailing list