I like how simple and straightforward it is to use pytest, which lets you write tests using assert <expression>. I wonder if it can be brought into pydantic to make validators easier to read and write.
from pydantic import BaseModel, validator
class AModel(BaseModel):
a_field: str
@validator('a_field')
def validate_a_field(cls, v):
assert 'hello' in v, 'v does not include hello'
Currently pydantic supports raising ValueError and TypeError [0]. Even though this change would be nothing but a syntactic sugar, I think it would be a nice addition to manually raising errors.
I've written the feature, added the tests and updated the docs in this PR: https://github.com/samuelcolvin/pydantic/pull/653
Personally I think this sounds like a great idea, but I have some questions/concerns:
types? eg. is this a value_error or should we have a new root type assertion_errorlet's give it at least a week for people to give feedback.
The one thing that stands out to me as a potential concern is that, if I understand correctly, assert statements are disabled when running python in "optimized mode", i.e. with the -O flag (this is discussed in some depth in this stack overflow answer: https://stackoverflow.com/questions/1273211/disable-assertions-in-python).
I'm not sure how commonly used that flag is (I think most people aren't even aware of the option), but I've always taken it as an indication that assert statements should be used for debugging, and never part of expected error handling (e.g., you generally shouldn't be catching/handling an AssertionError in production). Since validation errors may be expected during runtime even in production (e.g., if running a webserver that does json payload validation), using assert statements for validation could lead to unexpected behavior.
Presumably if you care about the -O flag, you are aware of the issues with asserts and would avoid them in your validators, so this feature would basically just be opt-in; given that, I could see arguments both for and against. But either way it probably should not be recommended without a warning.
(Obviously when using pytest, where I agree that assert statements provide a nice API, this consideration would not apply.)
I like it! :tada: :rocket:
And you have very clever concerns/insights in the comments above. I don't have anything else to say :sweat_smile:
I vote for this idea 馃憤
I think documents can cover some worry when using the feature.
Great, let's do it. PR welcome.
@samuelcolvin https://github.com/samuelcolvin/pydantic/pull/653
Let me know if you need anything
Thanks @pawelswiecki you're right !
Most helpful comment
Great, let's do it. PR welcome.