microsoft / pyright

Static Type Checker for Python
Other
12.7k stars 1.35k forks source link

`__replace__` should be synthesized for dataclasses in 3.13 #8300

Closed max-muoto closed 2 weeks ago

max-muoto commented 2 weeks ago

Starting in Python 3.13, a dunder __replace__ is added onto all dataclasses instances that effectively replicates the previous module level dataclasses.replace. See here for the relevant cpython PR.

The same goes for named tuples, but I'm not sure how much of that's special-cased by type-checkers versus is just in type-checkers.

erictraut commented 2 weeks ago

Changing from bug report to enhancement request.

I'm struggling to find documentation for this feature. I'd prefer to wait until it's documented before adding support. I'd also like to see support for copy.replace added to typeshed first, since the type information for this function will have a bearing on whether it is important to model the __replace__ method. Since this is a dunder method, it's presumably an implementation detail rather than something that would normally be called directly, but it may be important if it's exposed as a protocol in typeshed.

I'm going to decline the enhancement request for now because there are too many open questions, but I'm willing to reconsider this in the future.

max-muoto commented 2 weeks ago

Changing from bug report to enhancement request.

I'm struggling to find documentation for this feature. I'd prefer to wait until it's documented before adding support. I'd also like to see support for copy.replace added to typeshed first, since the type information for this function will have a bearing on whether it is important to model the __replace__ method. Since this is a dunder method, it's presumably an implementation detail rather than something that would normally be called directly, but it may be important if it's exposed as a protocol in typeshed.

I'm going to decline the enhancement request for now because there are too many open questions, but I'm willing to reconsider this in the future.

I currently have a PR open adding copy.replace to TypeShed for reference, where I implement a protocol that requires it, which is mainly why I'm creating this issue, but otherwise sounds good.

MyPy doesn't handle it for dataclass, but does for NamedTuple: https://github.com/python/mypy/pull/17259/files