python / python/mypy

dataclasses.dataclass, custom __init__ and dataclasses.replace false positive.

Open
#19,193 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-dataclasses
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I am not sure if this is a mypy bug or by design or maybe a missing feature, but at least looking at the runtime behavior it seems like a bug to me. I asked on gitter and one user responed that it seems to be a bug/oversight in the implementation.

I want to do converters with dataclasses, and the way to do this with dataclasses is to provide custom __init__ i.e. consider the following example.

To Reproduce

Playground link

import dataclasses

@dataclasses.dataclass
class WrapsInt:
   value: int
   
   def __init__(self, value: int | str):
       self.value = int(value)

wraps_int = WrapsInt("3")
print(repr(wraps_int.value))

wraps_int2 = dataclasses.replace(wraps_int, value="4")
print(repr(wraps_int2.value))

At runtime it will print and boths will be integers:

3
4

This is because dataclasses.replace always calls init. But mypy seems to take the type information from the class body only instead when analyzing dataclasses.replace call.

Expected Behavior

No error, mypy recognizes __init__ implementation when analyzing dataclass.replace calls.

Actual Behavior

main.py:16: error: Argument "value" to "replace" of "WrapsInt" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.15.0, master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): default
  • Python version used: 3.12

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the linked Playground reproducer or the provided Python example with mypy 1.15.0 or master and confirm the false positive from dataclasses.replace. Trace how dataclasses.replace derives the accepted field type, then verify that the completed change accepts the string argument while preserving the existing integer behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.