@@ -442,13 +442,11 @@ def _field_init(f, frozen, globals, self_name):
442
442
# This field does not need initialization. Signify that
443
443
# to the caller by returning None.
444
444
return None
445
-
446
445
# Only test this now, so that we can create variables for the
447
446
# default. However, return None to signify that we're not going
448
447
# to actually do the assignment statement for InitVars.
449
448
if f ._field_type == _FIELD_INITVAR :
450
449
return None
451
-
452
450
# Now, actually generate the field assignment.
453
451
return _field_assign (frozen , f .name , value , self_name )
454
452
@@ -490,7 +488,6 @@ def _init_fn(fields, frozen, has_post_init, self_name):
490
488
raise TypeError (
491
489
f"non-default argument { f .name !r} " "follows default argument"
492
490
)
493
-
494
491
globals = {"MISSING" : MISSING , "_HAS_DEFAULT_FACTORY" : _HAS_DEFAULT_FACTORY }
495
492
496
493
body_lines = []
@@ -500,16 +497,13 @@ def _init_fn(fields, frozen, has_post_init, self_name):
500
497
# initialization (it's a pseudo-field). Just skip it.
501
498
if line :
502
499
body_lines .append (line )
503
-
504
500
# Does this class have a post-init function?
505
501
if has_post_init :
506
502
params_str = "," .join (f .name for f in fields if f ._field_type is _FIELD_INITVAR )
507
503
body_lines .append (f"{ self_name } .{ _POST_INIT_NAME } ({ params_str } )" )
508
-
509
504
# If no body lines, use 'pass'.
510
505
if not body_lines :
511
506
body_lines = ["pass" ]
512
-
513
507
locals = {f"_type_{ f .name } " : f .type for f in fields }
514
508
return _create_fn (
515
509
"__init__" ,
@@ -674,7 +668,6 @@ def _get_field(cls, a_name, a_type):
674
668
# This is a field in __slots__, so it has no default value.
675
669
default = MISSING
676
670
f = field (default = default )
677
-
678
671
# Only at this point do we know the name and the type. Set them.
679
672
f .name = a_name
680
673
f .type = a_type
@@ -705,7 +698,6 @@ def _get_field(cls, a_name, a_type):
705
698
and _is_type (f .type , cls , typing , typing .ClassVar , _is_classvar )
706
699
):
707
700
f ._field_type = _FIELD_CLASSVAR
708
-
709
701
# If the type is InitVar, or if it's a matching string annotation,
710
702
# then it's an InitVar.
711
703
if f ._field_type is _FIELD :
@@ -717,7 +709,6 @@ def _get_field(cls, a_name, a_type):
717
709
and _is_type (f .type , cls , dataclasses , dataclasses .InitVar , _is_initvar )
718
710
):
719
711
f ._field_type = _FIELD_INITVAR
720
-
721
712
# Validations for individual fields. This is delayed until now,
722
713
# instead of in the Field() constructor, since only here do we
723
714
# know the field name, which allows for better error reporting.
@@ -731,14 +722,12 @@ def _get_field(cls, a_name, a_type):
731
722
# example, how about init=False (or really,
732
723
# init=<not-the-default-init-value>)? It makes no sense for
733
724
# ClassVar and InitVar to specify init=<anything>.
734
-
735
725
# For real fields, disallow mutable defaults for known types.
736
726
if f ._field_type is _FIELD and isinstance (f .default , (list , dict , set )):
737
727
raise ValueError (
738
728
f"mutable default { type (f .default )} for field "
739
729
f"{ f .name } is not allowed: use default_factory"
740
730
)
741
-
742
731
return f
743
732
744
733
@@ -827,7 +816,6 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
827
816
fields [f .name ] = f
828
817
if getattr (b , _PARAMS ).frozen :
829
818
any_frozen_base = True
830
-
831
819
# Annotations that are defined in this class (not in base
832
820
# classes). If __annotations__ isn't present, then this class
833
821
# adds no new annotations. We use this to compute fields that are
@@ -866,22 +854,18 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
866
854
delattr (cls , f .name )
867
855
else :
868
856
setattr (cls , f .name , f .default )
869
-
870
857
# Do we have any Field members that don't also have annotations?
871
858
for name , value in cls .__dict__ .items ():
872
859
if isinstance (value , Field ) and not name in cls_annotations :
873
860
raise TypeError (f"{ name !r} is a field but has no type annotation" )
874
-
875
861
# Check rules that apply if we are derived from any dataclasses.
876
862
if has_dataclass_bases :
877
863
# Raise an exception if any of our bases are frozen, but we're not.
878
864
if any_frozen_base and not frozen :
879
865
raise TypeError ("cannot inherit non-frozen dataclass from a " "frozen one" )
880
-
881
866
# Raise an exception if we're frozen, but none of our bases are.
882
867
if not any_frozen_base and frozen :
883
868
raise TypeError ("cannot inherit frozen dataclass from a " "non-frozen one" )
884
-
885
869
# Remember all of the fields on our class (including bases). This
886
870
# also marks this class as being a dataclass.
887
871
setattr (cls , _FIELDS , fields )
@@ -900,7 +884,6 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
900
884
# eq methods.
901
885
if order and not eq :
902
886
raise ValueError ("eq must be true if order is true" )
903
-
904
887
if init :
905
888
# Does this class have a post-init function?
906
889
has_post_init = hasattr (cls , _POST_INIT_NAME )
@@ -920,15 +903,13 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
920
903
"__dataclass_self__" if "self" in fields else "self" ,
921
904
),
922
905
)
923
-
924
906
# Get the fields as a list, and include only real fields. This is
925
907
# used in all of the following methods.
926
908
field_list = [f for f in fields .values () if f ._field_type is _FIELD ]
927
909
928
910
if repr :
929
911
flds = [f for f in field_list if f .repr ]
930
912
_set_new_attribute (cls , "__repr__" , _repr_fn (flds ))
931
-
932
913
if eq :
933
914
# Create _eq__ method. There's no need for a __ne__ method,
934
915
# since python will call __eq__ and negate it.
@@ -938,7 +919,6 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
938
919
_set_new_attribute (
939
920
cls , "__eq__" , _cmp_fn ("__eq__" , "==" , self_tuple , other_tuple )
940
921
)
941
-
942
922
if order :
943
923
# Create and set the ordering methods.
944
924
flds = [f for f in field_list if f .compare ]
@@ -958,15 +938,13 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
958
938
f"in class { cls .__name__ } . Consider using "
959
939
"functools.total_ordering"
960
940
)
961
-
962
941
if frozen :
963
942
for fn in _frozen_get_del_attr (cls , field_list ):
964
943
if _set_new_attribute (cls , fn .__name__ , fn ):
965
944
raise TypeError (
966
945
f"Cannot overwrite attribute { fn .__name__ } "
967
946
f"in class { cls .__name__ } "
968
947
)
969
-
970
948
# Decide if/how we're going to create a hash function.
971
949
hash_action = _hash_action [
972
950
bool (unsafe_hash ), bool (eq ), bool (frozen ), has_explicit_hash
@@ -975,11 +953,9 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
975
953
# No need to call _set_new_attribute here, since by the time
976
954
# we're here the overwriting is unconditional.
977
955
cls .__hash__ = hash_action (cls , field_list )
978
-
979
956
if not getattr (cls , "__doc__" ):
980
957
# Create a class doc-string.
981
958
cls .__doc__ = cls .__name__ + str (inspect .signature (cls )).replace (" -> None" , "" )
982
-
983
959
return cls
984
960
985
961
@@ -1015,7 +991,6 @@ def wrap(cls):
1015
991
if _cls is None :
1016
992
# We're called with parens.
1017
993
return wrap
1018
-
1019
994
# We're called as @dataclass without parens.
1020
995
return wrap (_cls )
1021
996
@@ -1032,7 +1007,6 @@ def fields(class_or_instance):
1032
1007
fields = getattr (class_or_instance , _FIELDS )
1033
1008
except AttributeError :
1034
1009
raise TypeError ("must be called with a dataclass type or instance" )
1035
-
1036
1010
# Exclude pseudo-fields. Note that fields is sorted by insertion
1037
1011
# order, so the order of the tuple is as the fields were defined.
1038
1012
return tuple (f for f in fields .values () if f ._field_type is _FIELD )
@@ -1174,7 +1148,6 @@ class C(Base):
1174
1148
else :
1175
1149
# Copy namespace since we're going to mutate it.
1176
1150
namespace = namespace .copy ()
1177
-
1178
1151
# While we're looking through the field names, validate that they
1179
1152
# are identifiers, are not keywords, and not duplicates.
1180
1153
seen = set ()
@@ -1184,23 +1157,23 @@ class C(Base):
1184
1157
name = item
1185
1158
tp = "typing.Any"
1186
1159
elif len (item ) == 2 :
1187
- name , tp , = item
1160
+ (
1161
+ name ,
1162
+ tp ,
1163
+ ) = item
1188
1164
elif len (item ) == 3 :
1189
1165
name , tp , spec = item
1190
1166
namespace [name ] = spec
1191
1167
else :
1192
1168
raise TypeError (f"Invalid field: { item !r} " )
1193
-
1194
1169
if not isinstance (name , str ) or not name .isidentifier ():
1195
1170
raise TypeError (f"Field names must be valid identifers: { name !r} " )
1196
1171
if keyword .iskeyword (name ):
1197
1172
raise TypeError (f"Field names must not be keywords: { name !r} " )
1198
1173
if name in seen :
1199
1174
raise TypeError (f"Field name duplicated: { name !r} " )
1200
-
1201
1175
seen .add (name )
1202
1176
anns [name ] = tp
1203
-
1204
1177
namespace ["__annotations__" ] = anns
1205
1178
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
1206
1179
# of generic dataclassses.
@@ -1229,14 +1202,13 @@ class C:
1229
1202
c = C(1, 2)
1230
1203
c1 = replace(c, x=3)
1231
1204
assert c1.x == 3 and c1.y == 2
1232
- """
1205
+ """
1233
1206
1234
1207
# We're going to mutate 'changes', but that's okay because it's a
1235
1208
# new dict, even if called with 'replace(obj, **my_changes)'.
1236
1209
1237
1210
if not _is_dataclass_instance (obj ):
1238
1211
raise TypeError ("replace() should be called on dataclass instances" )
1239
-
1240
1212
# It's an error to have init=False fields in 'changes'.
1241
1213
# If a field is not in 'changes', read its value from the provided obj.
1242
1214
@@ -1250,10 +1222,8 @@ class C:
1250
1222
"replace()"
1251
1223
)
1252
1224
continue
1253
-
1254
1225
if f .name not in changes :
1255
1226
changes [f .name ] = getattr (obj , f .name )
1256
-
1257
1227
# Create the new object, which calls __init__() and
1258
1228
# __post_init__() (if defined), using all of the init fields we've
1259
1229
# added and/or left in 'changes'. If there are values supplied in
0 commit comments