🚨 Set explicit stacklevel when warning about schema-wide many setting depending on initialization state.

This should help users see the exact line they wrote that triggered the warning.
This commit is contained in:
Daniil Fajnberg 2023-04-21 15:52:33 +02:00
parent 3c16b4ebd6
commit 862a517018
Signed by: daniil-berg
GPG Key ID: BE187C50903BEE97

View File

@ -16,6 +16,11 @@ from .decorators import post_load
Model = TypeVar("Model") Model = TypeVar("Model")
MANY_SCHEMA_UNSAFE = (
"Changing `many` schema-wide breaks type safety. "
"Use the the `many` parameter of specific methods (like `load`) instead."
)
class GenericSchema(GenericInsightMixin1[Model], Schema): class GenericSchema(GenericInsightMixin1[Model], Schema):
""" """
@ -100,6 +105,7 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
[`load`][marshmallow_generic.GenericSchema.load]/ [`load`][marshmallow_generic.GenericSchema.load]/
[`loads`][marshmallow_generic.GenericSchema.loads]. [`loads`][marshmallow_generic.GenericSchema.loads].
""" """
self._pre_init = True
super().__init__( super().__init__(
only=only, only=only,
exclude=exclude, exclude=exclude,
@ -110,6 +116,7 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
partial=partial, partial=partial,
unknown=unknown, unknown=unknown,
) )
self._pre_init = False
def __setattr__(self, name: str, value: Any) -> None: def __setattr__(self, name: str, value: Any) -> None:
""" """
@ -119,10 +126,7 @@ class GenericSchema(GenericInsightMixin1[Model], Schema):
[`object.__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__). [`object.__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__).
""" """
if name == "many" and value is not False: if name == "many" and value is not False:
warn( warn(MANY_SCHEMA_UNSAFE, stacklevel=4 if self._pre_init else 2)
"Changing `many` schema-wide breaks type safety. Use the the "
"`many` parameter of specific methods (like `load`) instead."
)
super().__setattr__(name, value) super().__setattr__(name, value)
@post_load @post_load