[issue47143] Add types.copy_class() which updates closures

Jelle Zijlstra report at bugs.python.org
Mon Mar 28 19:41:10 EDT 2022


Jelle Zijlstra <jelle.zijlstra at gmail.com> added the comment:

I mean that the code sample above from attrs doesn't properly update the closure for wrapped methods, such as those created by @functools.cache, or any other arbitrary decorator that creates a wrapper function.

Example (with Python 3.9.4 and attrs 21.4.0):

% cat attrslots.py 
import attr
import functools


class Base:
    @classmethod
    def f(cls):
        return 3


@attr.s(slots=True)
class Child(Base):
    x: int

    @classmethod
    @functools.cache
    def f(cls):
        return super().f() + 1


print(Child.f())
% python attrslots.py 
Traceback (most recent call last):
  File "/Users/jelle/py/pyanalyze/samples/attrslots.py", line 21, in <module>
    print(Child.f())
  File "/Users/jelle/py/pyanalyze/samples/attrslots.py", line 18, in f
    return super().f() + 1
TypeError: super(type, obj): obj must be an instance or subtype of type


If we provide a `types.copy_class()`, it should handle this case correctly.

----------

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


More information about the Python-bugs-list mailing list