Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃悰 Use the negative of allow_mutation on frozen Field #65

Merged
merged 2 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion bump_pydantic/codemods/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,15 @@ def leave_field_call(self, original_node: cst.Call, updated_node: cst.Call) -> c
for arg in updated_node.args:
if m.matches(arg, m.Arg(keyword=m.Name())):
keyword = RENAMED_KEYWORDS.get(arg.keyword.value, arg.keyword.value) # type: ignore
new_args.append(arg.with_changes(keyword=arg.keyword.with_changes(value=keyword))) # 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")
new_arg = arg.with_changes(keyword=arg.keyword.with_changes(value=keyword), value=value) # type: ignore
new_args.append(new_arg) # type: ignore
else:
new_args.append(arg)

Expand Down
17 changes: 17 additions & 0 deletions tests/unit/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,20 @@ class Potato(BaseModel):
potato: Literal[MyEnum.POTATO] = MyEnum.POTATO
"""
self.assertCodemod(before, after)

def test_flip_frozen_boolean(self) -> None:
before = """
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
potato: int = Field(..., allow_mutation=False)
strawberry: int = Field(..., allow_mutation=True)
"""
after = """
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
potato: int = Field(..., frozen=True)
strawberry: int = Field(..., frozen=False)
"""
self.assertCodemod(before, after)