generated from daniil-berg/boilerplate-py
Compare commits
No commits in common. "d272864e443db0b8ccebbc3bb9738e9d0b53de5c" and "fe5decad4f0a3e8f14a53c3c77f564462ded1f06" have entirely different histories.
d272864e44
...
fe5decad4f
4
.gitignore
vendored
4
.gitignore
vendored
@ -21,5 +21,5 @@ __pycache__/
|
||||
# Testing:
|
||||
/.coverage
|
||||
|
||||
# Miscellaneous cache:
|
||||
.cache/
|
||||
# mypy:
|
||||
.mypy_cache/
|
||||
|
@ -10,18 +10,19 @@
|
||||
|
||||
---
|
||||
|
||||
Extension for <a href="https://github.com/marshmallow-code/marshmallow" target="_blank">**`marshmallow`**</a> to make <a href="https://marshmallow.readthedocs.io/en/stable/quickstart.html#deserializing-to-objects" target="_blank">deserialization to objects</a> easier and improve type safety.
|
||||
Extension for <a href="https://github.com/marshmallow-code/marshmallow" target="_blank">`marshmallow`</a> to make <a href="https://marshmallow.readthedocs.io/en/stable/quickstart.html#deserializing-to-objects" target="_blank">deserialization to objects</a> easier and improve type safety.
|
||||
|
||||
The main `GenericSchema` class extends <a href="https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html#marshmallow.schema.Schema" target="_blank">`marshmallow.Schema`</a> making it **generic** in terms of the class that data should be deserialized to, when calling <a href="https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html#marshmallow.schema.Schema.load" target="_blank">`load`/`loads`</a>.
|
||||
|
||||
With `GenericSchema` there is no need to explicitly write `post_load` hooks to initialize the object anymore. 🎉
|
||||
|
||||
If the "model" class is (for example) `User`, it just needs to be passed as the type argument, when subclassing `GenericSchema`. The output of the `load`/`loads` method will then be automatically inferred as either `User` or `list[User]` (depending on whether `many` is `True` or not) by any competent type checker. ✨
|
||||
If the "model" class is (for example) `User`, it just needs to be passed as the type argument, when subclassing `GenericSchema`. Depending on whether `many` is `True` or not, the output of the `load`/`loads` method will then be automatically inferred as either `User` or `list[User]` by any competent type checker. ✨
|
||||
|
||||
## Usage Example
|
||||
|
||||
```python
|
||||
from marshmallow_generic import GenericSchema, fields
|
||||
from marshmallow import fields
|
||||
from marshmallow_generic import GenericSchema
|
||||
|
||||
|
||||
class User:
|
||||
|
@ -65,7 +65,6 @@ version = {attr = "marshmallow_generic.__version__"}
|
||||
# Static type checking: #
|
||||
|
||||
[tool.mypy]
|
||||
cache_dir = ".cache/mypy"
|
||||
files = [
|
||||
"src/",
|
||||
"tests/",
|
||||
@ -81,7 +80,6 @@ plugins = [
|
||||
# Unit test coverage: #
|
||||
|
||||
[tool.coverage.run]
|
||||
data_file = ".cache/coverage"
|
||||
source = [
|
||||
"src/",
|
||||
]
|
||||
@ -107,7 +105,6 @@ omit = [
|
||||
# Linting and style checking: #
|
||||
|
||||
[tool.ruff]
|
||||
cache-dir = ".cache/ruff"
|
||||
select = [
|
||||
"E", # pycodestyle errors
|
||||
"W", # pycodestyle warnings
|
||||
|
@ -19,41 +19,5 @@ __doc__ = """
|
||||
Generic schema with full typing support and minimal boilerplate.
|
||||
"""
|
||||
|
||||
__all__ = [
|
||||
# Custom:
|
||||
"GenericSchema",
|
||||
"post_load",
|
||||
# Re-exports from marshmallow:
|
||||
"EXCLUDE",
|
||||
"INCLUDE",
|
||||
"RAISE",
|
||||
"Schema",
|
||||
"SchemaOpts",
|
||||
"fields",
|
||||
"validates",
|
||||
"validates_schema",
|
||||
"pre_dump",
|
||||
"post_dump",
|
||||
"pre_load",
|
||||
# "post_load",
|
||||
"pprint",
|
||||
"ValidationError",
|
||||
"missing",
|
||||
]
|
||||
|
||||
from marshmallow import fields
|
||||
|
||||
from marshmallow.decorators import (
|
||||
post_dump,
|
||||
# post_load, # overloaded
|
||||
pre_dump,
|
||||
pre_load,
|
||||
validates,
|
||||
validates_schema,
|
||||
)
|
||||
from marshmallow.exceptions import ValidationError
|
||||
from marshmallow.schema import Schema, SchemaOpts
|
||||
from marshmallow.utils import EXCLUDE, INCLUDE, RAISE, missing, pprint
|
||||
|
||||
from marshmallow_generic.decorators import post_load
|
||||
from marshmallow_generic.schema import GenericSchema
|
||||
from .decorators import post_load
|
||||
from .schema import GenericSchema
|
||||
|
@ -54,10 +54,10 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
dump_only: Union[Sequence[str], set[str]] = (),
|
||||
partial: Union[bool, Sequence[str], set[str]] = False,
|
||||
unknown: Optional[str] = None,
|
||||
many: bool = False, # usage discouraged
|
||||
many: Optional[bool] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Emits a warning, if the `many` argument is not `False`.
|
||||
Emits a warning, if the `many` argument is not `None`.
|
||||
|
||||
Otherwise the same as in [`marshmallow.Schema`][marshmallow.Schema].
|
||||
|
||||
@ -72,34 +72,40 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
it is not used. Nested fields can be represented with dot
|
||||
delimiters.
|
||||
context:
|
||||
Optional context passed to
|
||||
[`Method`][marshmallow.fields.Method] and
|
||||
[`Function`][marshmallow.fields.Function] fields.
|
||||
Optional context passed to [`Method`]
|
||||
[marshmallow.fields.Method] and [`Function`]
|
||||
[marshmallow.fields.Function] fields.
|
||||
load_only:
|
||||
Fields to skip during serialization (write-only fields)
|
||||
dump_only:
|
||||
Fields to skip during deserialization (read-only fields)
|
||||
partial:
|
||||
Whether to ignore missing fields and not require any fields
|
||||
declared. Propagates down to
|
||||
[`Nested`][marshmallow.fields.Nested] fields as well. If its
|
||||
value is an iterable, only missing fields listed in that
|
||||
iterable will be ignored. Use dot delimiters to specify nested
|
||||
fields.
|
||||
declared. Propagates down to [`Nested`]
|
||||
[marshmallow.fields.Nested] fields as well. If its value is an
|
||||
iterable, only missing fields listed in that iterable will be
|
||||
ignored. Use dot delimiters to specify nested fields.
|
||||
unknown:
|
||||
Whether to exclude, include, or raise an error for unknown
|
||||
fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
|
||||
many:
|
||||
!!! warning
|
||||
Changing this option schema-wide undermines the type
|
||||
safety that this class aims to provide. Passing `True`
|
||||
will therefore trigger a warning. You should instead use
|
||||
the method-specific `many` parameter, when calling
|
||||
Specifying this option schema-wide undermines the type
|
||||
safety that this class aims to provide and passing any
|
||||
value other than `None` will trigger a warning. Use the
|
||||
method-specific `many` parameter, when calling
|
||||
[`dump`][marshmallow_generic.GenericSchema.dump]/
|
||||
[`dumps`][marshmallow_generic.GenericSchema.dumps] or
|
||||
[`load`][marshmallow_generic.GenericSchema.load]/
|
||||
[`loads`][marshmallow_generic.GenericSchema.loads].
|
||||
[`loads`][marshmallow_generic.GenericSchema.loads] instead.
|
||||
"""
|
||||
if many is not None:
|
||||
warn(
|
||||
"Setting `many` schema-wide breaks type safety. Use the the "
|
||||
"`many` parameter of specific methods (like `load`) instead."
|
||||
)
|
||||
else:
|
||||
many = bool(many)
|
||||
super().__init__(
|
||||
only=only,
|
||||
exclude=exclude,
|
||||
@ -111,28 +117,13 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
unknown=unknown,
|
||||
)
|
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None:
|
||||
"""
|
||||
Warns, when trying to set `many` to anything other than `False`.
|
||||
|
||||
Otherwise the same the normal
|
||||
[`object.__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__).
|
||||
"""
|
||||
if name == "many" and value is not False:
|
||||
warn(
|
||||
"Changing `many` schema-wide breaks type safety. Use the the "
|
||||
"`many` parameter of specific methods (like `load`) instead."
|
||||
)
|
||||
super().__setattr__(name, value)
|
||||
|
||||
@post_load
|
||||
def instantiate(self, data: dict[str, Any], **_kwargs: Any) -> Model:
|
||||
"""
|
||||
Unpacks `data` into the constructor of the specified **`Model`**.
|
||||
|
||||
Registered as a
|
||||
[`@post_load`][marshmallow_generic.decorators.post_load]
|
||||
hook for the schema.
|
||||
Registered as a [`@post_load`]
|
||||
[marshmallow_generic.decorators.post_load] hook for the schema.
|
||||
|
||||
!!! warning
|
||||
You should probably not use this method directly. No parsing,
|
||||
@ -178,9 +169,8 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
"""
|
||||
Serializes **`Model`** objects to native Python data types.
|
||||
|
||||
Same as
|
||||
[`marshmallow.Schema.dump`][marshmallow.schema.Schema.dump]
|
||||
at runtime.
|
||||
Same as [`marshmallow.Schema.dump`]
|
||||
[marshmallow.schema.Schema.dump] at runtime.
|
||||
|
||||
Annotations ensure that type checkers will infer the return type
|
||||
correctly based on the `many` argument, and also enforce the `obj`
|
||||
@ -264,10 +254,10 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
"""
|
||||
Deserializes data to objects of the specified **`Model`** class.
|
||||
|
||||
Same as
|
||||
[`marshmallow.Schema.load`][marshmallow.schema.Schema.load] at
|
||||
runtime, but data will always pass through the
|
||||
[`instantiate`][marshmallow_generic.schema.GenericSchema.instantiate]
|
||||
Same as [`marshmallow.Schema.load`]
|
||||
[marshmallow.schema.Schema.load] at runtime, but data will always
|
||||
pass through the [`instantiate`]
|
||||
[marshmallow_generic.schema.GenericSchema.instantiate]
|
||||
hook after deserialization.
|
||||
|
||||
Annotations ensure that type checkers will infer the return type
|
||||
@ -281,11 +271,11 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
the value for `self.many` is used.
|
||||
partial:
|
||||
Whether to ignore missing fields and not require any
|
||||
fields declared. Propagates down to
|
||||
[`Nested`][marshmallow.fields.Nested] fields as well. If
|
||||
its value is an iterable, only missing fields listed in
|
||||
that iterable will be ignored. Use dot delimiters to
|
||||
specify nested fields.
|
||||
fields declared. Propagates down to [`Nested`]
|
||||
[marshmallow.fields.Nested] fields as well. If its value
|
||||
is an iterable, only missing fields listed in that
|
||||
iterable will be ignored. Use dot delimiters to specify
|
||||
nested fields.
|
||||
unknown:
|
||||
Whether to exclude, include, or raise an error for unknown
|
||||
fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
|
||||
@ -333,10 +323,10 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
"""
|
||||
Deserializes data to objects of the specified **`Model`** class.
|
||||
|
||||
Same as
|
||||
[`marshmallow.Schema.loads`][marshmallow.schema.Schema.loads] at
|
||||
runtime, but data will always pass through the
|
||||
[`instantiate`][marshmallow_generic.schema.GenericSchema.instantiate]
|
||||
Same as [`marshmallow.Schema.loads`]
|
||||
[marshmallow.schema.Schema.loads] at runtime, but data will always
|
||||
pass through the [`instantiate`]
|
||||
[marshmallow_generic.schema.GenericSchema.instantiate]
|
||||
hook after deserialization.
|
||||
|
||||
Annotations ensure that type checkers will infer the return type
|
||||
@ -350,11 +340,11 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
|
||||
the value for `self.many` is used.
|
||||
partial:
|
||||
Whether to ignore missing fields and not require any
|
||||
fields declared. Propagates down to
|
||||
[`Nested`][marshmallow.fields.Nested] fields as well. If
|
||||
its value is an iterable, only missing fields listed in
|
||||
that iterable will be ignored. Use dot delimiters to
|
||||
specify nested fields.
|
||||
fields declared. Propagates down to [`Nested`]
|
||||
[marshmallow.fields.Nested] fields as well. If its value
|
||||
is an iterable, only missing fields listed in that
|
||||
iterable will be ignored. Use dot delimiters to specify
|
||||
nested fields.
|
||||
unknown:
|
||||
Whether to exclude, include, or raise an error for unknown
|
||||
fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
|
||||
|
@ -19,19 +19,15 @@ class GenericSchemaTestCase(TestCase):
|
||||
"dump_only": object(),
|
||||
"partial": object(),
|
||||
"unknown": object(),
|
||||
"many": object(),
|
||||
"many": None,
|
||||
}
|
||||
schema.GenericSchema[Foo](**kwargs)
|
||||
mock_super_init.assert_called_once_with(**kwargs)
|
||||
|
||||
def test___setattr__(self) -> None:
|
||||
class Foo:
|
||||
pass
|
||||
|
||||
obj = schema.GenericSchema[Foo]()
|
||||
mock_super_init.assert_called_once_with(**kwargs | {"many": False})
|
||||
mock_super_init.reset_mock()
|
||||
kwargs["many"] = True
|
||||
with self.assertWarns(UserWarning):
|
||||
obj.many = new = MagicMock()
|
||||
self.assertIs(new, obj.many)
|
||||
schema.GenericSchema[Foo](**kwargs)
|
||||
mock_super_init.assert_called_once_with(**kwargs)
|
||||
|
||||
@patch.object(_util.GenericInsightMixin, "_get_type_arg")
|
||||
def test_instantiate(self, mock__get_type_arg: MagicMock) -> None:
|
||||
|
Loading…
Reference in New Issue
Block a user