Context (experimental)¶
Helper API for setting serialization/deserialization context.
Example usage:
import typing
from marshmallow import Schema, fields
from marshmallow.experimental.context import Context
class UserContext(typing.TypedDict):
suffix: str
UserSchemaContext = Context[UserContext]
class UserSchema(Schema):
name_suffixed = fields.Function(
lambda user: user["name"] + UserSchemaContext.get()["suffix"]
)
with UserSchemaContext({"suffix": "bar"}):
print(UserSchema().dump({"name": "foo"}))
# {'name_suffixed': 'foobar'}
- class marshmallow.experimental.context.Context(context)[source]¶
Context manager for setting and retrieving context.
- Parameters:
context (_ContextT) – The context to use within the context manager scope.
- classmethod get(default=Ellipsis)[source]¶
Get the current context.
- Parameters:
default (_DefaultT | EllipsisType) – Default value to return if no context is set. If not provided and no context is set, a
LookupError
is raised.- Return type:
_ContextT | _DefaultT