Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
713a9367
Commit
713a9367
authored
May 16, 2018
by
Barry Warsaw
Committed by
GitHub
May 16, 2018
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
bpo-32216: Update dataclasses documentation (#6913)
parent
6d2cd903
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
79 additions
and
75 deletions
+79
-75
Doc/library/dataclasses.rst
Doc/library/dataclasses.rst
+79
-75
No files found.
Doc/library/dataclasses.rst
View file @
713a9367
...
@@ -117,50 +117,46 @@ Module-level decorators, classes, and functions
...
@@ -117,50 +117,46 @@ Module-level decorators, classes, and functions
:meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then
:meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then
:exc:`ValueError` is raised.
:exc:`ValueError` is raised.
- ``unsafe_hash``: If ``False`` (the default),
the
:meth:`__hash__` method
- ``unsafe_hash``: If ``False`` (the default),
a
:meth:`__hash__` method
is generated according to how ``eq`` and ``frozen`` are set.
is generated according to how ``eq`` and ``frozen`` are set.
If ``eq`` and ``frozen`` are both true, :func:`dataclass` will
:meth:`__hash__` is used by built-in :meth:`hash()`, and when objects are
generate a :meth:`__hash__` method for you. If ``eq`` is true
added to hashed collections such as dictionaries and sets. Having a
and ``frozen`` is false, :meth:`__hash__` will be set to
:meth:`__hash__` implies that instances of the class are immutable.
``None``, marking it unhashable (which it is, since it is
Mutability is a complicated property that depends on the programmer's
mutable). If ``eq`` is false, :meth:`__hash__` will be left
intent, the existence and behavior of :meth:`__eq__`, and the values of
untouched meaning the :meth:`__hash__` method of the superclass
the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator.
will be used (if the superclass is :class:`object`, this means it will
fall back to id-based hashing).
By default, :func:`dataclass` will not implicitly add a :meth:`__hash__`
method unless it is safe to do so. Neither will it add or change an
Although not recommended, you can force :func:`dataclass` to
existing explicitly defined :meth:`__hash__` method. Setting the class
create a :meth:`__hash__` method with ``unsafe_hash=True``. This
attribute ``__hash__ = None`` has a specific meaning to Python, as
might be the case if your class is logically immutable but can
described in the :meth:`__hash__` documentation.
nonetheless be mutated. This is a specialized use case and should
be considered carefully.
If :meth:`__hash__` is not explicit defined, or if it is set to ``None``,
then :func:`dataclass` *may* add an implicit :meth:`__hash__` method.
If a class already has an explicitely defined :meth:`__hash__`
Although not recommended, you can force :func:`dataclass` to create a
the behavior when adding :meth:`__hash__` is modified. An
:meth:`__hash__` method with ``unsafe_hash=True``. This might be the case
expicitely defined :meth:`__hash__` is defined when:
if your class is logically immutable but can nonetheless be mutated.
This is a specialized use case and should be considered carefully.
- :meth:`__eq__` is defined in the class and :meth:`__hash__` is defined
with any value other than ``None``.
Here are the rules governing implicit creation of a :meth:`__hash__`
method. Note that you cannot both have an explicit :meth:`__hash__`
- :meth:`__eq__` is defined in the class and any non-``None``
method in your dataclass and set ``unsafe_hash=True``; this will result
:meth:`__hash__` is defined.
in a :exc:`TypeError`.
- :meth:`__eq__` is not defined on the class, and any :meth:`__hash__` is
If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will
defined.
generate a :meth:`__hash__` method for you. If ``eq`` is true and
``frozen`` is false, :meth:`__hash__` will be set to ``None``, marking it
If ``unsafe_hash`` is true and an explicitely defined :meth:`__hash__`
unhashable (which it is, since it is mutable). If ``eq`` is false,
is present, then :exc:`ValueError` is raised.
:meth:`__hash__` will be left untouched meaning the :meth:`__hash__`
method of the superclass will be used (if the superclass is
If ``unsafe_hash`` is false and an explicitely defined :meth:`__hash__`
:class:`object`, this means it will fall back to id-based hashing).
is present, then no :meth:`__hash__` is added.
See the Python documentation for more information.
- ``frozen``: If true (the default is False), assigning to fields will
- ``frozen``: If true (the default is False), assigning to fields will
generate an exception. This emulates read-only frozen instances.
generate an exception. This emulates read-only frozen instances. If
If either :meth:`__getattr__` or :meth:`__setattr__` is defined in
:meth:`__setattr__` or :meth:`__delattr__` is defined in the class, then
the class, then :exc:`ValueError` is raised. See the discussion
:exc:`TypeError` is raised. See the discussion below.
below.
``field``\s may optionally specify a default value, using normal
``field``\s may optionally specify a default value, using normal
Python syntax::
Python syntax::
...
@@ -182,17 +178,17 @@ Module-level decorators, classes, and functions
...
@@ -182,17 +178,17 @@ Module-level decorators, classes, and functions
.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
For common and simple use cases, no other functionality is
For common and simple use cases, no other functionality is
required. There are, however, some
Data C
lass features that
required. There are, however, some
datac
lass features that
require additional per-field information. To satisfy this need for
require additional per-field information. To satisfy this need for
additional information, you can replace the default field value
additional information, you can replace the default field value
with a call to the provided :func:`field` function. For example::
with a call to the provided :func:`field` function. For example::
@dataclass
@dataclass
class C:
class C:
l
: List[int] = field(default_factory=list)
mylist
: List[int] = field(default_factory=list)
c = C()
c = C()
c.
l
+= [1, 2, 3]
c.
mylist
+= [1, 2, 3]
As shown above, the ``MISSING`` value is a sentinel object used to
As shown above, the ``MISSING`` value is a sentinel object used to
detect if the ``default`` and ``default_factory`` parameters are
detect if the ``default`` and ``default_factory`` parameters are
...
@@ -222,7 +218,7 @@ Module-level decorators, classes, and functions
...
@@ -222,7 +218,7 @@ Module-level decorators, classes, and functions
generated equality and comparison methods (:meth:`__eq__`,
generated equality and comparison methods (:meth:`__eq__`,
:meth:`__gt__`, et al.).
:meth:`__gt__`, et al.).
- ``hash``: This can be a bool or ``None``. If
T
rue, this field is
- ``hash``: This can be a bool or ``None``. If
t
rue, this field is
included in the generated :meth:`__hash__` method. If ``None`` (the
included in the generated :meth:`__hash__` method. If ``None`` (the
default), use the value of ``compare``: this would normally be
default), use the value of ``compare``: this would normally be
the expected behavior. A field should be considered in the hash
the expected behavior. A field should be considered in the hash
...
@@ -283,17 +279,16 @@ Module-level decorators, classes, and functions
...
@@ -283,17 +279,16 @@ Module-level decorators, classes, and functions
.. function:: fields(class_or_instance)
.. function:: fields(class_or_instance)
Returns a tuple of :class:`Field` objects
Returns a tuple of :class:`Field` objects that define the fields for this
that define the fields for this Data Class. Accepts either a Data
dataclass. Accepts either a dataclass, or an instance of a dataclass.
Class, or an instance of a Data Class. Raises :exc:`ValueError` if
Raises :exc:`TypeError` if not passed a dataclass or instance of one.
not passed a Data Class or instance of one. Does not return
Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``.
pseudo-fields which are ``ClassVar`` or ``InitVar``.
.. function:: asdict(instance, *, dict_factory=dict)
.. function:: asdict(instance, *, dict_factory=dict)
Converts the
Data C
lass ``instance`` to a dict (by using the
Converts the
datac
lass ``instance`` to a dict (by using the
factory function ``dict_factory``). Each
Data C
lass is converted
factory function ``dict_factory``). Each
datac
lass is converted
to a dict of its fields, as ``name: value`` pairs.
Data C
lasses, dicts,
to a dict of its fields, as ``name: value`` pairs.
datac
lasses, dicts,
lists, and tuples are recursed into. For example::
lists, and tuples are recursed into. For example::
@dataclass
@dataclass
...
@@ -303,21 +298,21 @@ Module-level decorators, classes, and functions
...
@@ -303,21 +298,21 @@ Module-level decorators, classes, and functions
@dataclass
@dataclass
class C:
class C:
l
: List[Point]
mylist
: List[Point]
p = Point(10, 20)
p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}
assert asdict(p) == {'x': 10, 'y': 20}
c = C([Point(0, 0), Point(10, 4)])
c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'
l
': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
assert asdict(c) == {'
mylist
': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
Raises :exc:`TypeError` if ``instance`` is not a
Data C
lass instance.
Raises :exc:`TypeError` if ``instance`` is not a
datac
lass instance.
.. function:: astuple(*, tuple_factory=tuple)
.. function:: astuple(*, tuple_factory=tuple)
Converts the
Data C
lass ``instance`` to a tuple (by using the
Converts the
datac
lass ``instance`` to a tuple (by using the
factory function ``tuple_factory``). Each
Data C
lass is converted
factory function ``tuple_factory``). Each
datac
lass is converted
to a tuple of its field values.
Data C
lasses, dicts, lists, and
to a tuple of its field values.
datac
lasses, dicts, lists, and
tuples are recursed into.
tuples are recursed into.
Continuing from the previous example::
Continuing from the previous example::
...
@@ -325,11 +320,11 @@ Module-level decorators, classes, and functions
...
@@ -325,11 +320,11 @@ Module-level decorators, classes, and functions
assert astuple(p) == (10, 20)
assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)
assert astuple(c) == ([(0, 0), (10, 4)],)
Raises :exc:`TypeError` if ``instance`` is not a
Data C
lass instance.
Raises :exc:`TypeError` if ``instance`` is not a
datac
lass instance.
.. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
.. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
Creates a new
Data C
lass with name ``cls_name``, fields as defined
Creates a new
datac
lass with name ``cls_name``, fields as defined
in ``fields``, base classes as given in ``bases``, and initialized
in ``fields``, base classes as given in ``bases``, and initialized
with a namespace as given in ``namespace``. ``fields`` is an
with a namespace as given in ``namespace``. ``fields`` is an
iterable whose elements are each either ``name``, ``(name, type)``,
iterable whose elements are each either ``name``, ``(name, type)``,
...
@@ -341,7 +336,7 @@ Module-level decorators, classes, and functions
...
@@ -341,7 +336,7 @@ Module-level decorators, classes, and functions
This function is not strictly required, because any Python
This function is not strictly required, because any Python
mechanism for creating a new class with ``__annotations__`` can
mechanism for creating a new class with ``__annotations__`` can
then apply the :func:`dataclass` function to convert that class to
then apply the :func:`dataclass` function to convert that class to
a
Data C
lass. This function is provided as a convenience. For
a
datac
lass. This function is provided as a convenience. For
example::
example::
C = make_dataclass('C',
C = make_dataclass('C',
...
@@ -369,14 +364,14 @@ Module-level decorators, classes, and functions
...
@@ -369,14 +364,14 @@ Module-level decorators, classes, and functions
specify fields, raises :exc:`TypeError`.
specify fields, raises :exc:`TypeError`.
The newly returned object is created by calling the :meth:`__init__`
The newly returned object is created by calling the :meth:`__init__`
method of the
Data C
lass. This ensures that
method of the
datac
lass. This ensures that
:meth:`__post_init__`, if present, is also called.
:meth:`__post_init__`, if present, is also called.
Init-only variables without default values, if any exist, must be
Init-only variables without default values, if any exist, must be
specified on the call to :func:`replace` so that they can be passed to
specified on the call to :func:`replace` so that they can be passed to
:meth:`__init__` and :meth:`__post_init__`.
:meth:`__init__` and :meth:`__post_init__`.
It is an error for
:func:`changes
` to contain any fields that are
It is an error for
``changes`
` to contain any fields that are
defined as having ``init=False``. A :exc:`ValueError` will be raised
defined as having ``init=False``. A :exc:`ValueError` will be raised
in this case.
in this case.
...
@@ -408,7 +403,7 @@ The generated :meth:`__init__` code will call a method named
...
@@ -408,7 +403,7 @@ The generated :meth:`__init__` code will call a method named
:meth:`__post_init__`, if :meth:`__post_init__` is defined on the
:meth:`__post_init__`, if :meth:`__post_init__` is defined on the
class. It will normally be called as ``self.__post_init__()``.
class. It will normally be called as ``self.__post_init__()``.
However, if any ``InitVar`` fields are defined, they will also be
However, if any ``InitVar`` fields are defined, they will also be
passed to :meth:`__post_init` in the order they were defined in the
passed to :meth:`__post_init
__
` in the order they were defined in the
class. If no :meth:`__init__` method is generated, then
class. If no :meth:`__init__` method is generated, then
:meth:`__post_init__` will not automatically be called.
:meth:`__post_init__` will not automatically be called.
...
@@ -435,7 +430,7 @@ One of two places where :func:`dataclass` actually inspects the type
...
@@ -435,7 +430,7 @@ One of two places where :func:`dataclass` actually inspects the type
of a field is to determine if a field is a class variable as defined
of a field is to determine if a field is a class variable as defined
in :pep:`526`. It does this by checking if the type of the field is
in :pep:`526`. It does this by checking if the type of the field is
``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded
``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded
from consideration as a field and is ignored by the
Data C
lass
from consideration as a field and is ignored by the
datac
lass
mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
module-level :func:`fields` function.
module-level :func:`fields` function.
...
@@ -450,7 +445,7 @@ field. As it is not a true field, it is not returned by the
...
@@ -450,7 +445,7 @@ field. As it is not a true field, it is not returned by the
module-level :func:`fields` function. Init-only fields are added as
module-level :func:`fields` function. Init-only fields are added as
parameters to the generated :meth:`__init__` method, and are passed to
parameters to the generated :meth:`__init__` method, and are passed to
the optional :meth:`__post_init__` method. They are not otherwise used
the optional :meth:`__post_init__` method. They are not otherwise used
by
Data C
lasses.
by
datac
lasses.
For example, suppose a field will be initialzed from a database, if a
For example, suppose a field will be initialzed from a database, if a
value is not provided when creating the class::
value is not provided when creating the class::
...
@@ -475,7 +470,7 @@ Frozen instances
...
@@ -475,7 +470,7 @@ Frozen instances
It is not possible to create truly immutable Python objects. However,
It is not possible to create truly immutable Python objects. However,
by passing ``frozen=True`` to the :meth:`dataclass` decorator you can
by passing ``frozen=True`` to the :meth:`dataclass` decorator you can
emulate immutability. In that case,
Data C
lasses will add
emulate immutability. In that case,
datac
lasses will add
:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These
:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These
methods will raise a :exc:`FrozenInstanceError` when invoked.
methods will raise a :exc:`FrozenInstanceError` when invoked.
...
@@ -486,9 +481,9 @@ must use :meth:`object.__setattr__`.
...
@@ -486,9 +481,9 @@ must use :meth:`object.__setattr__`.
Inheritance
Inheritance
-----------
-----------
When the
Data C
lass is being created by the :meth:`dataclass` decorator,
When the
datac
lass is being created by the :meth:`dataclass` decorator,
it looks through all of the class's base classes in reverse MRO (that
it looks through all of the class's base classes in reverse MRO (that
is, starting at :class:`object`) and, for each
Data C
lass that it finds,
is, starting at :class:`object`) and, for each
datac
lass that it finds,
adds the fields from that base class to an ordered mapping of fields.
adds the fields from that base class to an ordered mapping of fields.
After all of the base class fields are added, it adds its own fields
After all of the base class fields are added, it adds its own fields
to the ordered mapping. All of the generated methods will use this
to the ordered mapping. All of the generated methods will use this
...
@@ -520,7 +515,7 @@ Default factory functions
...
@@ -520,7 +515,7 @@ Default factory functions
zero arguments when a default value for the field is needed. For
zero arguments when a default value for the field is needed. For
example, to create a new instance of a list, use::
example, to create a new instance of a list, use::
l
: list = field(default_factory=list)
mylist
: list = field(default_factory=list)
If a field is excluded from :meth:`__init__` (using ``init=False``)
If a field is excluded from :meth:`__init__` (using ``init=False``)
and the field also specifies ``default_factory``, then the default
and the field also specifies ``default_factory``, then the default
...
@@ -532,7 +527,7 @@ Mutable default values
...
@@ -532,7 +527,7 @@ Mutable default values
----------------------
----------------------
Python stores default member variable values in class attributes.
Python stores default member variable values in class attributes.
Consider this example, not using
Data C
lasses::
Consider this example, not using
datac
lasses::
class C:
class C:
x = []
x = []
...
@@ -549,7 +544,7 @@ Mutable default values
...
@@ -549,7 +544,7 @@ Mutable default values
Note that the two instances of class ``C`` share the same class
Note that the two instances of class ``C`` share the same class
variable ``x``, as expected.
variable ``x``, as expected.
Using
Data C
lasses, *if* this code was valid::
Using
datac
lasses, *if* this code was valid::
@dataclass
@dataclass
class D:
class D:
...
@@ -571,9 +566,9 @@ Mutable default values
...
@@ -571,9 +566,9 @@ Mutable default values
This has the same issue as the original example using class ``C``.
This has the same issue as the original example using class ``C``.
That is, two instances of class ``D`` that do not specify a value for
That is, two instances of class ``D`` that do not specify a value for
``x`` when creating a class instance will share the same copy of
``x`` when creating a class instance will share the same copy of
``x``. Because
Data C
lasses just use normal Python class creation
``x``. Because
datac
lasses just use normal Python class creation
they also share this
problem
. There is no general way for Data
they also share this
behavior
. There is no general way for Data
Classes to detect this condition. Instead,
Data C
lasses will raise a
Classes to detect this condition. Instead,
datac
lasses will raise a
:exc:`TypeError` if it detects a default parameter of type ``list``,
:exc:`TypeError` if it detects a default parameter of type ``list``,
``dict``, or ``set``. This is a partial solution, but it does protect
``dict``, or ``set``. This is a partial solution, but it does protect
against many common errors.
against many common errors.
...
@@ -586,3 +581,12 @@ Mutable default values
...
@@ -586,3 +581,12 @@ Mutable default values
x: list = field(default_factory=list)
x: list = field(default_factory=list)
assert D().x is not D().x
assert D().x is not D().x
Exceptions
----------
.. exception:: FrozenInstanceError
Raised when an implicitly defined :meth:`__setattr__` or
:meth:`__delattr__` is called on a dataclass which was defined with
``frozen=True``.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment