[New-bugs-announce] [issue33805] dataclasses: replace() give poor error message if using InitVar

Eric V. Smith report at bugs.python.org
Fri Jun 8 04:51:39 EDT 2018


New submission from Eric V. Smith <eric at trueblade.com>:

If a dataclass contains an InitVar without a default value, that InitVar must be specified in the call to replace(). This is because replace() works by first creating a new object, and InitVars without defaults, by definition, must be specified when creating the object. There is no other source for the value of the InitVar to use.

However, the exception you get is confusing:

>>> from dataclasses import *
>>> @dataclass
... class C:
...   i: int
...   j: InitVar[int]
...
>>> c = C(1, 2)
>>> replace(c, i=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\home\eric\local\python\cpython\lib\dataclasses.py", line 1176, in replace
    changes[f.name] = getattr(obj, f.name)
AttributeError: 'C' object has no attribute 'j'
>>>

This message really should say something like "InitVar 'j' must be specified".

----------
assignee: eric.smith
components: Library (Lib)
messages: 319036
nosy: eric.smith
priority: normal
severity: normal
status: open
title: dataclasses: replace() give poor error message if using InitVar
type: behavior
versions: Python 3.7, Python 3.8

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


More information about the New-bugs-announce mailing list