-
Notifications
You must be signed in to change notification settings - Fork 26
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’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Need rules for each_item
and always
#70
Comments
What are you proposing here? |
RulesBP0xy: Replace
|
each_item
and always
each_item
and always
I'm using a def validator_for_each_list_item(item: str):
...
class A(BaseModel):
my_list: List[Annotated[str, BeforeValidator(validator_for_each_list_item)]] Not sure if this is doable with a codemod |
Well... It's feasible. I guess what would be faster is to teach how to do it via comment. |
Given the |
Were |
Let's do |
Then... If from pydantic import BaseModel, validator
class User(BaseModel):
first_names: List[str]
last_names: List[str]
@validator("first_name", "last_name", each_item=True)
def names_must_not_be_empty_strings(cls, v):
if v:
return v
raise ValueError("Empty strings are not permitted") Then we'd get: from pydantic import BaseModel, validator, BeforeValidator
from typing_extensions import Annotated
from typing import List
# This function goes to the outer scope.
# I think we can get the `ClassDef` parent node with `LibCST.ParentProvider`. But I'm not sure...
def names_must_not_be_empty_strings(v):
if v:
return v
raise ValueError("Empty strings are not permitted")
class User(BaseModel):
# Check if the `AnnAssign.annotation` (List in this case) is a `Subscriptable` - and if it's, apply `BeforeValidator`.
first_names: List[Annotated[str, BeforeValidator(names_must_not_be_empty_strings)]]
last_names: List[Annotated[str, BeforeValidator(names_must_not_be_empty_strings)]] Remember to import Also, you might want to check function name collision on the module level - but I'm not sure if this is needed - but an Not finished yet... If the number of params is more than 2, then add a note on top of the method: # TODO: We couldn't replace the validator automatically.
# Please check https://docs.pydantic.dev/latest/migration/#validator-and-root_validator-are-deprecated. |
bump-pydantic/bump_pydantic/codemods/validator.py
Lines 92 to 93 in 47c66de
https://docs.pydantic.dev/dev-v2/migration/#changes-to-validators
The text was updated successfully, but these errors were encountered: