diff options
author | Eric V. Smith <ericvsmith@users.noreply.github.com> | 2021-12-11 21:12:17 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-12-11 21:12:17 (GMT) |
commit | e029c53e1a408b89a4e3edf30a9b38b094f9c880 (patch) | |
tree | a439835a4dd477b67b500e5d09ff82b739973791 /Doc/library/dataclasses.rst | |
parent | bfc59ed0a00106f5ba4a32a0c5b3dbe71d12665d (diff) | |
download | cpython-e029c53e1a408b89a4e3edf30a9b38b094f9c880.zip cpython-e029c53e1a408b89a4e3edf30a9b38b094f9c880.tar.gz cpython-e029c53e1a408b89a4e3edf30a9b38b094f9c880.tar.bz2 |
bpo-44674: Use unhashability as a proxy for mutability for default dataclass __init__ arguments. (GH-29867)
`@dataclass` in 3.10 prohibits using list, dict, or set as default values. It does this to avoid the mutable default problem. This test is both too strict, and not strict enough. Too strict, because some immutable subclasses should be safe, and not strict enough, because other mutable types should be prohibited. With this change applied, `@dataclass` now uses unhashability as a proxy for mutability: if objects aren't hashable, they're assumed to be mutable.
Diffstat (limited to 'Doc/library/dataclasses.rst')
-rw-r--r-- | Doc/library/dataclasses.rst | 12 |
1 files changed, 9 insertions, 3 deletions
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index b065470..3592429 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -712,9 +712,9 @@ Mutable default values creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the :func:`dataclass` decorator will raise a :exc:`TypeError` if it - detects a default parameter of type ``list``, ``dict``, or ``set``. - This is a partial solution, but it does protect against many common - errors. + detects an unhashable default parameter. The assumption is that if + a value is unhashable, it is mutable. This is a partial solution, + but it does protect against many common errors. Using default factory functions is a way to create new instances of mutable types as default values for fields:: @@ -724,3 +724,9 @@ Mutable default values x: list = field(default_factory=list) assert D().x is not D().x + + .. versionchanged:: 3.11 + Instead of looking for and disallowing objects of type ``list``, + ``dict``, or ``set``, unhashable objects are now not allowed as + default values. Unhashability is used to approximate + mutability. |