Skip to content

Commit

Permalink
Convert example parameter into examples on Field (#122)
Browse files Browse the repository at this point in the history
Co-authored-by: Marcelo Trylesinski <[email protected]>
  • Loading branch information
Gamrix and Kludex committed Sep 18, 2023
1 parent 849f34b commit e0a6ba9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
17 changes: 11 additions & 6 deletions bump_pydantic/codemods/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"min_items": "min_length",
"max_items": "max_length",
"allow_mutation": "frozen",
"example": "examples",
"regex": "pattern",
# NOTE: This is only for BaseSettings.
"env": "validation_alias",
Expand Down Expand Up @@ -115,12 +116,16 @@ def leave_field_call(self, original_node: cst.Call, updated_node: cst.Call) -> c
if m.matches(arg, m.Arg(keyword=m.Name())):
keyword = RENAMED_KEYWORDS.get(arg.keyword.value, arg.keyword.value) # type: ignore
value = arg.value
# The `allow_mutation` keyword argument is a special case. It's the negative of `frozen`.
if arg.keyword and arg.keyword.value == "allow_mutation":
if m.matches(arg.value, m.Name(value="False")):
value = cst.Name("True")
elif m.matches(arg.value, m.Name(value="True")):
value = cst.Name("False")
if arg.keyword:
if arg.keyword.value == "allow_mutation":
# The `allow_mutation` keyword is the negative of `frozen`.
if m.matches(arg.value, m.Name(value="False")):
value = cst.Name("True")
elif m.matches(arg.value, m.Name(value="True")):
value = cst.Name("False")
if arg.keyword.value == "example":
# The example keyword is now a list, `examples`.
value = cst.List([cst.Element(arg.value)])
new_arg = arg.with_changes(keyword=arg.keyword.with_changes(value=keyword), value=value) # type: ignore
new_args.append(new_arg) # type: ignore
else:
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,18 @@ class Potato(BaseModel):
potato: Annotated[List[int], Field(..., min_length=1, max_length=10)]
"""
self.assertCodemod(before, after)

def test_example_list(self) -> None:
before = """
from pydantic import BaseSettings, Field
class Settings(BaseSettings):
potato: int = Field(..., example=1)
"""
after = """
from pydantic import BaseSettings, Field
class Settings(BaseSettings):
potato: int = Field(..., examples=[1])
"""
self.assertCodemod(before, after)

0 comments on commit e0a6ba9

Please sign in to comment.