Skip to content

Commit

Permalink
Exemplify using type aliases for Context
Browse files Browse the repository at this point in the history
  • Loading branch information
sloria authored and lafrech committed Jan 5, 2025
1 parent f1cbe27 commit 63d46aa
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 5 additions & 2 deletions docs/upgrading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,16 @@ manager class that can be used to both set and retrieve context.
suffix: str
UserSchemaContext = Context[UserContext]
class UserSchema(Schema):
name_suffixed = fields.Function(
lambda obj: obj["name"] + Context[UserContext].get()["suffix"]
lambda obj: obj["name"] + UserSchemaContext.get()["suffix"]
)
with Context[UserContext]({"suffix": "bar"}):
with UserSchemaContext({"suffix": "bar"}):
UserSchema().dump({"name": "foo"})
# {'name_suffixed': 'foobar'}
Expand Down
7 changes: 5 additions & 2 deletions src/marshmallow/experimental/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ class UserContext(typing.TypedDict):
suffix: str
UserSchemaContext = Context[UserContext]
class UserSchema(Schema):
name_suffixed = fields.Function(
lambda user: user["name"] + Context[UserContext].get()["suffix"]
lambda user: user["name"] + UserSchemaContext.get()["suffix"]
)
with Context[UserContext]({"suffix": "bar"}):
with UserSchemaContext({"suffix": "bar"}):
print(UserSchema().dump({"name": "foo"}))
# {'name_suffixed': 'foobar'}
"""
Expand Down

0 comments on commit 63d46aa

Please sign in to comment.