@@ -31,13 +31,15 @@ variables with type annotations as defined in PEP 526, "Syntax for
31
31
Variable Annotations". In this document, such variables are called
32
32
fields. Using these fields, the decorator adds generated method
33
33
definitions to the class to support instance initialization, a repr,
34
- comparisons methods, and optionally other methods as described in the
34
+ comparison methods, and optionally other methods as described in the
35
35
Specification _ section. Such a class is called a Data Class, but
36
36
there's really nothing special about the class: the decorator adds
37
37
generated methods to the class and returns the same class it was
38
38
given.
39
39
40
- As an example::
40
+ As an example:
41
+
42
+ .. code :: python
41
43
42
44
@dataclass
43
45
class InventoryItem :
@@ -50,7 +52,9 @@ As an example::
50
52
return self .unit_price * self .quantity_on_hand
51
53
52
54
The ``@dataclass `` decorator will add the equivalent of these methods
53
- to the InventoryItem class::
55
+ to the InventoryItem class:
56
+
57
+ .. code :: python
54
58
55
59
def __init__ (self , name : str , unit_price : float , quantity_on_hand : int = 0 ) -> None :
56
60
self .name = name
@@ -83,7 +87,7 @@ to the InventoryItem class::
83
87
return (self .name, self .unit_price, self .quantity_on_hand) >= (other.name, other.unit_price, other.quantity_on_hand)
84
88
return NotImplemented
85
89
86
- Data Classes saves you from writing and maintaining these methods.
90
+ Data Classes save you from writing and maintaining these methods.
87
91
88
92
Rationale
89
93
=========
@@ -164,13 +168,17 @@ class that is called on: no new class is created.
164
168
165
169
The ``dataclass `` decorator is typically used with no parameters and
166
170
no parentheses. However, it also supports the following logical
167
- signature::
171
+ signature:
172
+
173
+ .. code :: python
168
174
169
175
def dataclass (* , init = True , repr = True , eq = True , order = True , hash = None , frozen = False )
170
176
171
177
If ``dataclass `` is used just as a simple decorator with no
172
178
parameters, it acts as if it has the default values documented in this
173
- signature. That is, these three uses of ``@dataclass `` are equivalent::
179
+ signature. That is, these three uses of ``@dataclass `` are equivalent:
180
+
181
+ .. code :: python
174
182
175
183
@dataclass
176
184
class C :
@@ -186,10 +194,10 @@ signature. That is, these three uses of ``@dataclass`` are equivalent::
186
194
187
195
The parameters to ``dataclass `` are:
188
196
189
- - ``init ``: If true (the default), a ``__init__ `` method will be
197
+ - ``init ``: If true (the default), an ``__init__ `` method will be
190
198
generated.
191
199
192
- - ``repr ``: If true (the default), a ``__repr__ `` method will be
200
+ - ``repr ``: If true (the default), an ``__repr__ `` method will be
193
201
generated. The generated repr string will have the class name and
194
202
the name and repr of each field, in the order they are defined in
195
203
the class. Fields that are marked as being excluded from the repr
@@ -231,15 +239,19 @@ The parameters to ``dataclass`` are:
231
239
See the discussion below.
232
240
233
241
``field ``'s may optionally specify a default value, using normal
234
- Python syntax::
242
+ Python syntax:
243
+
244
+ .. code :: python
235
245
236
246
@dataclass
237
247
class C :
238
248
a: int # 'a' has no default value
239
249
b: int = 0 # assign a default value for 'b'
240
250
241
251
In this example, both ``a `` and ``b `` will be included in the added
242
- ``__init__ `` method, which will be defined as::
252
+ ``__init__ `` method, which will be defined as:
253
+
254
+ .. code :: python
243
255
244
256
def __init__ (self , a : int , b : int = 0 ):
245
257
@@ -251,7 +263,9 @@ For common and simple use cases, no other functionality is required.
251
263
There are, however, some Data Class features that require additional
252
264
per-field information. To satisfy this need for additional
253
265
information, you can replace the default field value with a call to
254
- the provided ``field() `` function. The signature of ``field() `` is::
266
+ the provided ``field() `` function. The signature of ``field() `` is:
267
+
268
+ .. code :: python
255
269
256
270
def field (* , default = _MISSING , default_factory = _MISSING , repr = True ,
257
271
hash = None , init = True , compare = True , metadata = None )
@@ -309,7 +323,9 @@ specified ``default`` value. If no ``default`` is provided, then the
309
323
class attribute will be deleted. The intent is that after the
310
324
``dataclass `` decorator runs, the class attributes will all contain
311
325
the default values for the fields, just as if the default value itself
312
- were specified. For example, after::
326
+ were specified. For example, after:
327
+
328
+ .. code :: python
313
329
314
330
@dataclass
315
331
class C :
@@ -350,7 +366,9 @@ as ``self.__post_init__()``. If not ``__init__`` method is generated,
350
366
then ``__post_init__ `` will not automatically be called.
351
367
352
368
Among other uses, this allows for initializing field values that
353
- depend on one or more other fields. For example::
369
+ depend on one or more other fields. For example:
370
+
371
+ .. code :: python
354
372
355
373
@dataclass
356
374
class C :
@@ -390,7 +408,9 @@ the optional ``__post_init__`` method. They are not otherwise used
390
408
by Data Classes.
391
409
392
410
For example, suppose a field will be initialzed from a database, if a
393
- value is not provided when creating the class::
411
+ value is not provided when creating the class:
412
+
413
+ .. code :: python
394
414
395
415
@dataclass
396
416
class C :
@@ -431,7 +451,9 @@ After all of the base class fields are added, it adds its own fields
431
451
to the ordered mapping. All of the generated methods will use this
432
452
combined, calculated ordered mapping of fields. Because the fields
433
453
are in insertion order, derived classes override base classes. An
434
- example::
454
+ example:
455
+
456
+ .. code :: python
435
457
436
458
@dataclass
437
459
class Base :
@@ -446,7 +468,9 @@ example::
446
468
The final list of fields is, in order, ``x ``, ``y ``, ``z ``. The final
447
469
type of ``x `` is ``int ``, as specified in class ``C ``.
448
470
449
- The generated ``__init__ `` method for ``C `` will look like::
471
+ The generated ``__init__ `` method for ``C `` will look like:
472
+
473
+ .. code :: python
450
474
451
475
def __init__ (self , x : int = 15 , y : int = 0 , z : int = 10 ):
452
476
@@ -455,7 +479,9 @@ Default factory functions
455
479
456
480
If a field specifies a ``default_factory ``, it is called with zero
457
481
arguments when a default value for the field is needed. For example,
458
- to create a new instance of a list, use::
482
+ to create a new instance of a list, use:
483
+
484
+ .. code :: python
459
485
460
486
l: list = field(default_factory = list )
461
487
@@ -469,7 +495,9 @@ Mutable default values
469
495
----------------------
470
496
471
497
Python stores default member variable values in class attributes.
472
- Consider this example, not using Data Classes::
498
+ Consider this example, not using Data Classes:
499
+
500
+ .. code :: python
473
501
474
502
class C :
475
503
x = []
@@ -486,15 +514,19 @@ Consider this example, not using Data Classes::
486
514
Note that the two instances of class ``C `` share the same class
487
515
variable ``x ``, as expected.
488
516
489
- Using Data Classes, *if * this code was valid::
517
+ Using Data Classes, *if * this code was valid:
518
+
519
+ .. code :: python
490
520
491
521
@dataclass
492
522
class D :
493
523
x: List = []
494
524
def add (self , element ):
495
525
self .x += element
496
526
497
- it would generate code similar to::
527
+ it would generate code similar to:
528
+
529
+ .. code :: python
498
530
499
531
class D :
500
532
x = []
@@ -517,7 +549,9 @@ against many common errors. See `Automatically support mutable
517
549
default values `_ in the Rejected Ideas section for more details.
518
550
519
551
Using default factory functions is a way to create new instances of
520
- mutable types as default values for fields::
552
+ mutable types as default values for fields:
553
+
554
+ .. code :: python
521
555
522
556
@dataclass
523
557
class D :
@@ -538,7 +572,9 @@ Module level helper functions
538
572
``instance `` to a dict (by using the factory function
539
573
``dict_factory ``). Each Data Class is converted to a dict of its
540
574
fields, as name:value pairs. Data Classes, dicts, lists, and tuples
541
- are recursed into. For example::
575
+ are recursed into. For example:
576
+
577
+ .. code:: python
542
578
543
579
@dataclass
544
580
class Point:
@@ -563,7 +599,9 @@ Module level helper functions
563
599
field values. Data Classes, dicts, lists, and tuples are recursed
564
600
into.
565
601
566
- Continuing from the previous example::
602
+ Continuing from the previous example:
603
+
604
+ .. code:: python
567
605
568
606
assert astuple(p) == (10, 20)
569
607
assert astuple(c) == ([(0, 0), (10, 4)],)
@@ -580,14 +618,18 @@ Module level helper functions
580
618
strictly required, because any Python mechanism for creating a new
581
619
class with ``__annotations__ `` can then apply the ``dataclass ``
582
620
function to convert that class to a Data Class. This function is
583
- provided as a convenience. For example::
621
+ provided as a convenience. For example:
622
+
623
+ .. code :: python
584
624
585
625
C = make_dataclass(' C' ,
586
626
[(' x' , int ),
587
627
(' y' , int , field(default = 5 ))],
588
628
namespace = {' add_one' : lambda self : self .x + 1 })
589
629
590
- Is equivalent to::
630
+ Is equivalent to:
631
+
632
+ .. code :: python
591
633
592
634
@dataclass
593
635
class C :
@@ -667,15 +709,19 @@ Why not just use namedtuple?
667
709
False.
668
710
669
711
- Instances are always iterable, which can make it difficult to add
670
- fields. If a library defines::
712
+ fields. If a library defines:
713
+
714
+ .. code :: python
671
715
672
- Time = namedtuple('Time', ['hour', 'minute'])
673
- def get_time():
674
- return Time(12, 0)
716
+ Time = namedtuple('Time', ['hour', 'minute'])
717
+ def get_time():
718
+ return Time(12, 0)
675
719
676
- Then if a user uses this code as::
720
+ Then if a user uses this code as:
721
+
722
+ .. code:: python
677
723
678
- hour, minute = get_time()
724
+ hour, minute = get_time()
679
725
680
726
then it would not be possible to add a ``second `` field to ``Time ``
681
727
without breaking the user's code.
@@ -719,7 +765,9 @@ post-init function ``__post_init__`` never took any parameters.
719
765
720
766
The normal way of doing parameterized initialization (and not just
721
767
with Data Classes) is to provide an alternate classmethod constructor.
722
- For example::
768
+ For example:
769
+
770
+ .. code :: python
723
771
724
772
@dataclass
725
773
class C :
@@ -770,7 +818,9 @@ A previous version of this PEP specified that ``init=False`` fields
770
818
would be copied from the source object to the newly created object
771
819
after ``__init__ `` returned, but that was deemed to be inconsistent
772
820
with using ``__init__ `` and ``__post_init__ `` to initialize the new
773
- object. For example, consider this case::
821
+ object. For example, consider this case:
822
+
823
+ .. code :: python
774
824
775
825
@dataclass
776
826
class Square :
@@ -806,7 +856,9 @@ Custom __init__ method
806
856
807
857
Sometimes the generated ``__init__ `` method does not suffice. For
808
858
example, suppose you wanted to have an object to store ``*args `` and
809
- ``**kwargs ``::
859
+ ``**kwargs ``:
860
+
861
+ .. code :: python
810
862
811
863
@dataclass (init = False )
812
864
class ArgHolder :
@@ -822,7 +874,9 @@ example, suppose you wanted to have an object to store ``*args`` and
822
874
A complicated example
823
875
---------------------
824
876
825
- This code exists in a closed source project::
877
+ This code exists in a closed source project:
878
+
879
+ .. code :: python
826
880
827
881
class Application :
828
882
def __init__ (self , name , requirements , constraints = None , path = ' ' , executable_links = None , executables_dir = ()):
@@ -837,7 +891,9 @@ This code exists in a closed source project::
837
891
def __repr__ (self ):
838
892
return f ' Application( { self .name!r } , { self .requirements!r } , { self .constraints!r } , { self .path!r } , { self .executable_links!r } , { self .executables_dir!r } , { self .additional_items!r } ) '
839
893
840
- This can be replaced by::
894
+ This can be replaced by:
895
+
896
+ .. code :: python
841
897
842
898
@dataclass
843
899
class Application :
0 commit comments