Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev chores #2226

Merged
merged 8 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Run tox -e lint
  • Loading branch information
sloria committed Jan 17, 2024
commit c6437e6ff1ddb1b4af8a222458f56ec293c19b7e
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,6 @@ venv
.mypy_cache/
.dmypy.json
dmypy.json

# ruff
.ruff_cache
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import datetime as dt
import os
import sys
import time
import datetime as dt

import alabaster

Expand Down
3 changes: 2 additions & 1 deletion examples/flask_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import NoResultFound
from marshmallow import Schema, fields, ValidationError, pre_load

from marshmallow import Schema, ValidationError, fields, pre_load

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/quotes.db"
Expand Down
7 changes: 4 additions & 3 deletions examples/package_json_example.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sys
import json
from packaging import version
import sys
from pprint import pprint

from marshmallow import Schema, fields, INCLUDE, ValidationError
from packaging import version

from marshmallow import INCLUDE, Schema, ValidationError, fields


class Version(fields.Field):
Expand Down
9 changes: 5 additions & 4 deletions examples/peewee_example.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import datetime as dt
from functools import wraps

from flask import Flask, request, g, jsonify
import peewee as pw
from flask import Flask, g, jsonify, request

from marshmallow import (
Schema,
ValidationError,
fields,
validate,
pre_load,
post_dump,
post_load,
ValidationError,
pre_load,
validate,
)

app = Flask(__name__)
Expand Down
3 changes: 2 additions & 1 deletion examples/textblob_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from bottle import route, request, run
from bottle import request, route, run
from textblob import TextBlob

from marshmallow import Schema, fields


Expand Down
4 changes: 2 additions & 2 deletions performance/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
"""
import argparse
import cProfile
import datetime
import gc
import timeit
import datetime

from marshmallow import Schema, fields, ValidationError, post_dump
from marshmallow import Schema, ValidationError, fields, post_dump


# Custom validator
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ show-fixes = true
show-source = true

[tool.ruff.lint]
ignore = ["E203", "E266", "E501", "E731"]
select = [
"B", # flake8-bugbear
"E", # pycodestyle error
Expand All @@ -74,6 +75,9 @@ select = [
"W", # pycodestyle warning
]

[tool.ruff.per-file-ignores]
"tests/*" = ["E721"]

[tool.mypy]
ignore_missing_imports = true
warn_unreachable = true
Expand Down
1 change: 1 addition & 0 deletions src/marshmallow/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import importlib.metadata

from packaging.version import Version

from marshmallow.decorators import (
Expand Down
1 change: 1 addition & 0 deletions src/marshmallow/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Users should not need to use this module directly.
"""
from __future__ import annotations

from abc import ABC, abstractmethod


Expand Down
9 changes: 5 additions & 4 deletions src/marshmallow/class_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from __future__ import annotations

import typing

from marshmallow.exceptions import RegistryError

if typing.TYPE_CHECKING:
Expand Down Expand Up @@ -76,16 +77,16 @@ def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaTyp
classes = _registry[classname]
except KeyError as error:
raise RegistryError(
"Class with name {!r} was not found. You may need "
"to import the class.".format(classname)
f"Class with name {classname!r} was not found. You may need "
"to import the class."
) from error
if len(classes) > 1:
if all:
return _registry[classname]
raise RegistryError(
"Multiple classes with name {!r} "
f"Multiple classes with name {classname!r} "
"were found. Please use the full, "
"module-qualified path.".format(classname)
"module-qualified path."
)
else:
return _registry[classname][0]
1 change: 0 additions & 1 deletion src/marshmallow/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import typing


# Key used for schema-level validation errors
SCHEMA = "_schema"

Expand Down
54 changes: 26 additions & 28 deletions src/marshmallow/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,30 @@
import collections
import copy
import datetime as dt
import numbers
import uuid
import ipaddress
import decimal
import ipaddress
import math
import numbers
import typing
import uuid
import warnings
from enum import Enum as EnumType
from collections.abc import Mapping as _Mapping
from enum import Enum as EnumType

from marshmallow import validate, utils, class_registry, types
from marshmallow import class_registry, types, utils, validate
from marshmallow.base import FieldABC, SchemaABC
from marshmallow.exceptions import (
FieldInstanceResolutionError,
StringNotCollectionError,
ValidationError,
)
from marshmallow.utils import (
is_aware,
is_collection,
missing as missing_,
resolve_field_instance,
is_aware,
)
from marshmallow.exceptions import (
ValidationError,
StringNotCollectionError,
FieldInstanceResolutionError,
from marshmallow.utils import (
missing as missing_,
)
from marshmallow.validate import And, Length
from marshmallow.warnings import RemovedInMarshmallow4Warning
Expand Down Expand Up @@ -237,14 +239,12 @@ def __init__(

def __repr__(self) -> str:
return (
"<fields.{ClassName}(dump_default={self.dump_default!r}, "
"attribute={self.attribute!r}, "
"validate={self.validate}, required={self.required}, "
"load_only={self.load_only}, dump_only={self.dump_only}, "
"load_default={self.load_default}, allow_none={self.allow_none}, "
"error_messages={self.error_messages})>".format(
ClassName=self.__class__.__name__, self=self
)
f"<fields.{self.__class__.__name__}(dump_default={self.dump_default!r}, "
f"attribute={self.attribute!r}, "
f"validate={self.validate}, required={self.required}, "
f"load_only={self.load_only}, dump_only={self.dump_only}, "
f"load_default={self.load_default}, allow_none={self.allow_none}, "
f"error_messages={self.error_messages})>"
)

def __deepcopy__(self, memo):
Expand Down Expand Up @@ -281,9 +281,9 @@ def make_error(self, key: str, **kwargs) -> ValidationError:
except KeyError as error:
class_name = self.__class__.__name__
message = (
"ValidationError raised by `{class_name}`, but error key `{key}` does "
f"ValidationError raised by `{class_name}`, but error key `{key}` does "
"not exist in the `error_messages` dictionary."
).format(class_name=class_name, key=key)
)
raise AssertionError(message) from error
if isinstance(msg, (str, bytes)):
msg = msg.format(**kwargs)
Expand All @@ -297,9 +297,7 @@ def fail(self, key: str, **kwargs):
Use `make_error <marshmallow.fields.Field.make_error>` instead.
"""
warnings.warn(
'`Field.fail` is deprecated. Use `raise self.make_error("{}", ...)` instead.'.format(
key
),
f'`Field.fail` is deprecated. Use `raise self.make_error("{key}", ...)` instead.',
RemovedInMarshmallow4Warning,
stacklevel=2,
)
Expand Down Expand Up @@ -611,7 +609,7 @@ def schema(self):
elif not isinstance(nested, (str, bytes)):
raise ValueError(
"`Nested` fields must be passed a "
"`Schema`, not {}.".format(nested.__class__)
f"`Schema`, not {nested.__class__}."
)
elif nested == "self":
schema_class = self.root.__class__
Expand Down Expand Up @@ -1827,9 +1825,9 @@ def _serialize(self, value, attr, obj, **kwargs) -> str | None:
return value.exploded
return value.compressed

def _deserialize(
self, value, attr, data, **kwargs
) -> None | (ipaddress.IPv4Interface | ipaddress.IPv6Interface):
def _deserialize(self, value, attr, data, **kwargs) -> None | (
ipaddress.IPv4Interface | ipaddress.IPv6Interface
):
if value is None:
return None
try:
Expand Down
35 changes: 17 additions & 18 deletions src/marshmallow/schema.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
"""The :class:`Schema` class, including its metaclass and options (class Meta)."""
from __future__ import annotations
from abc import ABCMeta

from collections import defaultdict, OrderedDict
from collections.abc import Mapping
from functools import lru_cache
import copy
import datetime as dt
import uuid
import decimal
import copy
import inspect
import json
import typing
import uuid
import warnings
from abc import ABCMeta
from collections import OrderedDict, defaultdict
from collections.abc import Mapping
from functools import lru_cache

from marshmallow import base, fields as ma_fields, class_registry, types
from marshmallow.error_store import ErrorStore
from marshmallow.exceptions import ValidationError, StringNotCollectionError
from marshmallow.orderedset import OrderedSet
from marshmallow import base, class_registry, types
from marshmallow import fields as ma_fields
from marshmallow.decorators import (
POST_DUMP,
POST_LOAD,
Expand All @@ -26,15 +24,18 @@
VALIDATES,
VALIDATES_SCHEMA,
)
from marshmallow.error_store import ErrorStore
from marshmallow.exceptions import StringNotCollectionError, ValidationError
from marshmallow.orderedset import OrderedSet
from marshmallow.utils import (
RAISE,
EXCLUDE,
INCLUDE,
missing,
set_value,
RAISE,
get_value,
is_collection,
is_instance_or_subclass,
missing,
set_value,
validate_unknown_parameter_value,
)
from marshmallow.warnings import RemovedInMarshmallow4Warning
Expand Down Expand Up @@ -407,9 +408,7 @@ def __init__(
self.error_messages = messages

def __repr__(self) -> str:
return "<{ClassName}(many={self.many})>".format(
ClassName=self.__class__.__name__, self=self
)
return f"<{self.__class__.__name__}(many={self.many})>"

@property
def dict_class(self) -> type:
Expand Down Expand Up @@ -1004,7 +1003,7 @@ def _init_fields(self) -> None:
"The data_key argument for one or more fields collides "
"with another field's name or data_key argument. "
"Check the following field names and "
"data_key arguments: {}".format(list(data_keys_duplicates))
f"data_key arguments: {list(data_keys_duplicates)}"
)
load_attributes = [obj.attribute or name for name, obj in load_fields.items()]
if len(load_attributes) != len(set(load_attributes)):
Expand All @@ -1015,7 +1014,7 @@ def _init_fields(self) -> None:
"The attribute argument for one or more fields collides "
"with another field's name or attribute argument. "
"Check the following field names and "
"attribute arguments: {}".format(list(attributes_duplicates))
f"attribute arguments: {list(attributes_duplicates)}"
)

self.fields = fields_dict
Expand Down
7 changes: 2 additions & 5 deletions src/marshmallow/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from __future__ import annotations

import collections
import functools
import datetime as dt
import functools
import inspect
import json
import re
Expand Down Expand Up @@ -311,10 +311,7 @@ def set_value(dct: dict[str, typing.Any], key: str, value: typing.Any):
target = dct.setdefault(head, {})
if not isinstance(target, dict):
raise ValueError(
"Cannot set {key} in {head} "
"due to existing value: {target}".format(
key=key, head=head, target=target
)
f"Cannot set {key} in {head} " f"due to existing value: {target}"
)
set_value(target, rest, value)
else:
Expand Down
7 changes: 3 additions & 4 deletions src/marshmallow/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ def __repr__(self) -> str:
args = self._repr_args()
args = f"{args}, " if args else ""

return "<{self.__class__.__name__}({args}error={self.error!r})>".format(
self=self, args=args
)
return f"<{self.__class__.__name__}({args}error={self.error!r})>"

def _repr_args(self) -> str:
"""A string representation of the args passed to this validator. Used by
Expand Down Expand Up @@ -237,7 +235,8 @@ class Email(Validator):

DOMAIN_REGEX = re.compile(
# domain
r"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+" r"(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\Z"
r"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+"
r"(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\Z"
# literal form, ipv4 address (SMTP 4.1.3)
r"|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)"
r"(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]\Z",
Expand Down
Loading