8000 Replace type comments with inline typing (#2718) · marshmallow-code/marshmallow@f4ca03f · GitHub
[go: up one dir, main page]

Skip to content

Commit f4ca03f

Browse files
authored
Replace type comments with inline typing (#2718)
* Replace type comments with inline typing * Update changelog
1 parent 1a58c1f commit f4ca03f

File tree

5 files changed

+46
-36
lines changed

5 files changed

+46
-36
lines changed

CHANGELOG.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
Changelog
22
---------
33

4+
3.24.0 (unreleased)
5+
*******************
6+
7+
Features:
8+
9+
- Typing: Replace type comments with inline typings (:pr:`2718`).
10+
11+
412
3.23.3 (2025-01-03)
513
*******************
614

src/marshmallow/fields.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def __init__(
218218
)
219219

220220
# Collect default error message from self and parent classes
221-
messages = {} # type: dict[str, str]
221+
messages: dict[str, str] = {}
222222
for cls in reversed(self.__class__.__mro__):
223223
messages.update(getattr(cls, "default_error_messages", {}))
224224
messages.update(error_messages or {})
@@ -919,7 +919,7 @@ class Number(Field):
919919
:param kwargs: The same keyword arguments that :class:`Field` receives.
920920
"""
921921

922-
num_type = float # type: typing.Type
922+
num_type: type = float
923923

924924
#: Default error messages.
925925
default_error_messages = {
@@ -956,7 +956,7 @@ def _serialize(self, value, attr, obj, **kwargs) -> str | _T | None:
956956
"""Return a string if `self.as_string=True`, otherwise return this field's `num_type`."""
957957
if value is None:
958958
return None
959-
ret = self._format_num(value) # type: _T
959+
ret: _T = self._format_num(value)
960960
return self._to_string(ret) if self.as_string else ret
961961

962962
def _deserialize(self, value, attr, data, **kwargs) -> _T | None:
@@ -1213,23 +1213,23 @@ class DateTime(Field):
12131213
Add timestamp as a format.
12141214
"""
12151215

1216-
SERIALIZATION_FUNCS = {
1216+
SERIALIZATION_FUNCS: dict[str, typing.Callable[[typing.Any], str | float]] = {
12171217
"iso": utils.isoformat,
12181218
"iso8601": utils.isoformat,
12191219
"rfc": utils.rfcformat,
12201220
"rfc822": utils.rfcformat,
12211221
"timestamp": utils.timestamp,
12221222
"timestamp_ms": utils.timestamp_ms,
1223-
} # type: dict[str, typing.Callable[[typing.Any], str | float]]
1223+
}
12241224

1225-
DESERIALIZATION_FUNCS = {
1225+
DESERIALIZATION_FUNCS: dict[str, typing.Callable[[str], typing.Any]] = {
12261226
"iso": utils.from_iso_datetime,
12271227
"iso8601": utils.from_iso_datetime,
12281228
"rfc": utils.from_rfc,
12291229
"rfc822": utils.from_rfc,
12301230
"timestamp": utils.from_timestamp,
12311231
"timestamp_ms": utils.from_timestamp_ms,
1232-
} # type: dict[str, typing.Callable[[str], typing.Any]]
1232+
}
12331233

12341234
DEFAULT_FORMAT = "iso"
12351235

@@ -1732,7 +1732,7 @@ class IP(Field):
17321732

17331733
default_error_messages = {"invalid_ip": "Not a valid IP address."}
17341734

1735-
DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type]
1735+
DESERIALIZATION_CLASS: type | None = None
17361736

17371737
def __init__(self, *args, exploded=False, **kwargs):
17381738
super().__init__(*args, **kwargs)
@@ -1796,7 +1796,7 @@ class IPInterface(Field):
17961796

17971797
default_error_messages = {"invalid_ip_interface": "Not a valid IP interface."}
17981798

1799-
DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type]
1799+
DESERIALIZATION_CLASS: type | None = None
18001800

18011801
def __init__(self, *args, exploded: bool = False, **kwargs):
18021802
super().__init__(*args, **kwargs)

src/marshmallow/schema.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def resolve_hooks(cls) -> dict[str, list[tuple[str, bool, dict]]]:
154154
"""
155155
mro = inspect.getmro(cls)
156156

157-
hooks = defaultdict(list) # type: dict[str, list[tuple[str, bool, dict]]]
157+
hooks: dict[str, list[tuple[str, bool, dict]]] = defaultdict(list)
158158

159159
for attr_name in dir(cls):
160160
# Need to look up the actual descriptor, not whatever might be
@@ -174,7 +174,9 @@ def resolve_hooks(cls) -> dict[str, list[tuple[str, bool, dict]]]:
174174
continue
175175

176176
try:
177-
hook_config = attr.__marshmallow_hook__ # type: dict[str, list[tuple[bool, dict]]]
177+
hook_config: dict[str, list[tuple[bool, dict]]] = (
178+
attr.__marshmallow_hook__
179+
)
178180
except AttributeError:
179181
pass
180182
else:
@@ -282,7 +284,7 @@ class AlbumSchema(Schema):
282284
`prefix` parameter removed.
283285
"""
284286

285-
TYPE_MAPPING = {
287+
TYPE_MAPPING: dict[type, type[ma_fields.Field]] = {
286288
str: ma_fields.String,
287289
bytes: ma_fields.String,
288290
dt.datetime: ma_fields.DateTime,
@@ -297,23 +299,23 @@ class AlbumSchema(Schema):
297299
dt.date: ma_fields.Date,
298300
dt.timedelta: ma_fields.TimeDelta,
299301
decimal.Decimal: ma_fields.Decimal,
300-
} # type: dict[type, typing.Type[ma_fields.Field]]
302+
}
301303
#: Overrides for default schema-level error messages
302-
error_messages = {} # type: dict[str, str]
304+
error_messages: dict[str, str] = {}
303305

304-
_default_error_messages = {
306+
_default_error_messages: dict[str, str] = {
305307
"type": "Invalid input type.",
306308
"unknown": "Unknown field.",
307-
} # type: dict[str, str]
309+
}
308310

309-
OPTIONS_CLASS = SchemaOpts # type: type
311+
OPTIONS_CLASS: type = SchemaOpts
310312

311313
set_class = OrderedSet
312314

313315
# These get set by SchemaMeta
314-
opts = None # type: SchemaOpts
315-
_declared_fields = {} # type: dict[str, ma_fields.Field]
316-
_hooks = {} # type: dict[str, list[tuple[str, bool, dict]]]
316+
opts: SchemaOpts
317+
_declared_fields: dict[str, ma_fields.Field] = {}
318+
_hooks: dict[str, list[tuple[str, bool, dict]]] = {}
317319

318320
class Meta:
319321
"""Options object for a Schema.
@@ -391,9 +393,9 @@ def __init__(
391393
self.context = context or {}
392394
self._normalize_nested_options()
393395
#: Dictionary mapping field_names -> :class:`Field` objects
394-
self.fields = {} # type: dict[str, ma_fields.Field]
395-
self.load_fields = {} # type: dict[str, ma_fields.Field]
396-
self.dump_fields = {} # type: dict[str, ma_fields.Field]
396+
self.fields: dict[str, ma_fields.Field] = {}
397+
self.load_fields: dict[str, ma_fields.Field] = {}
398+
self.dump_fields: dict[str, ma_fields.Field] = {}
397399
self._init_fields()
398400
messages = {}
399401
messages.update(self._default_error_messages)
@@ -821,7 +823,7 @@ def _do_load(
821823
:return: Deserialized data
822824
"""
823825
error_store = ErrorStore()
824-
errors = {} # type: dict[str, list[str]]
826+
errors: dict[str, list[str]] = {}
825827
many = self.many if many is None else bool(many)
826828
unknown = (
827829
self.unknown
@@ -838,7 +840,7 @@ def _do_load(
838840
)
839841
except ValidationError as err:
840842
errors = err.normalized_messages()
841-
result = None # type: list | dict | None
843+
result: list | dict | None = None
842844
else:
843845
processed_data = data
844846
if not errors:

src/marshmallow/validate.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Validator(ABC):
2222
add a useful `__repr__` implementation for validators.
2323
"""
2424

25-
error = None # type: str | None
25+
error: str | None = None
2626

2727
def __repr__(self) -> str:
2828
args = self._repr_args()
@@ -65,7 +65,7 @@ def is_even(value):
6565

6666
def __init__(self, *validators: types.Validator, error: str | None = None):
6767
self.validators = tuple(validators)
68-
self.error = error or self.default_error_message # type: str
68+
self.error: str = error or self.default_error_message
6969

7070
def _repr_args(self) -> str:
7171
return f"validators={self.validators!r}"
@@ -191,7 +191,7 @@ def __init__(
191191
)
192192
self.relative = relative
193193
self.absolute = absolute
194-
self.error = error or self.default_message # type: str
194+
self.error: str = error or self.default_message
195195
self.schemes = schemes or self.default_schemes
196196
self.require_tld = require_tld
197197

@@ -250,7 +250,7 @@ class Email(Validator):
250250
default_message = "Not a valid email address."
251251

252252
def __init__(self, *, error: str | None = None):
253-
self.error = error or self.default_message # type: str
253+
self.error: str = error or self.default_message
254254

255255
def _format_error(self, value: str) -> str:
256256
return self.error.format(input=value)
@@ -436,7 +436,7 @@ class Equal(Validator):
436436

437437
def __init__(self, comparable, *, error: str | None = None):
438438
self.comparable = comparable
439-
self.error = error or self.default_message # type: str
439+
self.error: str = error or self.default_message
440440

441441
def _repr_args(self) -> str:
442442
return f"comparable={self.comparable!r}"
@@ -477,7 +477,7 @@ def __init__(
477477
self.regex = (
478478
re.compile(regex, flags) if isinstance(regex, (str, bytes)) else regex
479479
)
480-
self.error = error or self.default_message # type: str
480+
self.error: str = error or self.default_message
481481

482482
def _repr_args(self) -> str:
483483
return f"regex={self.regex!r}"
@@ -514,7 +514,7 @@ class Predicate(Validator):
514514

515515
def __init__(self, method: str, *, error: str | None = None, **kwargs):
516516
self.method = method
517-
self.error = error or self.default_message # type: str
517+
self.error: str = error or self.default_message
518518
self.kwargs = kwargs
519519

520520
def _repr_args(self) -> str:
@@ -545,7 +545,7 @@ class NoneOf(Validator):
545545
def __init__(self, iterable: typing.Iterable, *, error: str | None = None):
546546
self.iterable = iterable
547547
self.values_text = ", ".join(str(each) for each in self.iterable)
548-
self.error = error or self.default_message # type: str
548+
self.error: str = error or self.default_message
549549

550550
def _repr_args(self) -> str:
551551
return f"iterable={self.iterable!r}"
@@ -585,7 +585,7 @@ def __init__(
585585
self.choices_text = ", ".join(str(choice) for choice in self.choices)
586586
self.labels = labels if labels is not None else []
587587
self.labels_text = ", ".join(str(label) for label in self.labels)
588-
self.error = error or self.default_message # type: str
588+
self.error: str = error or self.default_message
589589

590590
def _repr_args(self) -> str:
591591
return f"choices={self.choices!r}, labels={self.labels!r}"

tests/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ def get_lowername(obj):
180180

181181
class UserSchema(Schema):
182182
name = fields.String()
183-
age = fields.Float() # type: fields.Field
183+
age: fields.Field = fields.Float()
184184
created = fields.DateTime()
185185
created_formatted = fields.DateTime(
186186
format="%Y-%m-%d", attribute="created", dump_only=True
@@ -193,7 +193,7 @@ class UserSchema(Schema):
193193
homepage = fields.Url()
194194
email = fields.Email()
195195
balance = fields.Decimal()
196-
is_old = fields.Method("get_is_old") # type: fields.Field
196+
is_old: fields.Field = fields.Method("get_is_old")
197197
lowername = fields.Function(get_lowername)
198198
registered = fields.Boolean()
199199
hair_colors = fields.List(fields.Raw)

0 commit comments

Comments
 (0)
0