-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
validate_assignment decorator improvements #1205
Comments
Python Version: 3.8 Using the decorator on v1.17 with arguments seems to mangle the function signature in vscode, specifically with their pylance language server. Haven't tested @validate_arguments(config=dict(arbitrary_types_allowed=True))
# or
@validate_arguments(config=None)
# modifies signature from def foo(a:int,b:str)->str:... to def foo()->Any: The validation still seems to work correctly, but all intellisense is lost.
Pycharm with |
The only feature so far that I wish I ran into this in the context of building a convenience interface to a web service that takes some query parameters. Example import enum
from typing import List
import httpx
from pydantic import validate_arguments
class Status(str, enum.Enum):
available = "available"
pending = "pending"
sold = "sold"
@validate_arguments
def find_pets_by_status(status: List[Status]) -> List[dict]:
r = httpx.get("https://petstore.swagger.io/v2/pet/findByStatus", params={"status": status})
print(r.request.url)
return r.json()
print(find_pets_by_status(["pending", "sold"]))
>>>https://petstore.swagger.io/v2/pet/findByStatus?status=Status.sold&status=Status.pending
>>>[] The solution is easy enough, just extract the values for the enum. Is this perhaps something we could just make default behavior if the enum is a mixin type? |
I think
This is not to say that such a field should be validated, it should simply be ignored by |
My use case for
The issue with this is it also catches any It would be useful to be able to get the validated arguments separately from executing the function. Is this possible already, without effectively writing my own version of |
@PrettyWood I had not, and that seems to do the job. Thanks! One minor nitpick I would mention is mypy can't understand it, but that isn't a showstopper. What I ideally want is a way to get the validated arguments (handling exceptions), and then call the function with the validated arguments. Is there a way to get the validated args and kwargs from |
Note that #1272 added support for instance-methods; the checkbox should be checked. |
Not sure if this is the correct place for this issue but I've been trying to add the Pydantic seems to continuously call from pydantic import annotated_types
create_model_from_typeddict = annotated_types.create_model_from_typeddict
def patched_create_model(
typeddict_cls: Type[Any], **kwargs: Any
) -> Type[BaseModel]:
if hasattr(typeddict_cls, '__pydantic_model__'):
return typeddict_cls.__pydantic_model__
kwargs.setdefault('__module__', typeddict_cls.__module__)
model = create_model_from_typeddict(typeddict_cls, **kwargs)
typeddict_cls.__pydantic_model__ = model
return model
annotated_types.create_model_from_typeddict = patched_create_model I'm using the development version of pydantic, installed from GitHub. Here's a minimal repro that will crash with a recursion error: from pydantic import validate_arguments
from typing import Optional, TypedDict
class UserCreateInput(TypedDict):
name: str
post: 'PostCreateInput'
class PostCreateInput(TypedDict):
title: str
author: Optional['UserCreateInput']
@validate_arguments
def create_user(data: UserCreateInput) -> None:
print(data)
create_user({'name': 'Robert'}) Edit: Just realised an issue was just created for this bug: #3297 |
I would also suggest adding an argument to make model creation lazy. I'm using e.g. |
Just following up on my earlier question above about getting the validated args and kwargs, I see that this is possible:
Can someone speak to whether there is a better way to achieve this? Better as in less hacky and likely to continue to work? |
Hi all! I wrote a decorator to do custom validation on fields and args when a method is called. Pydantic does custom validation of fields at object instantiation, which works for many use cases but is inflexible for others (e.g. for optional fields that are used only in some methods). Pydantic can do basic validation on arguments, but not custom validation. Please correct me if I'm wrong on either of those two points :). The logic looks something like this:
The validator object takes a callable and the string representation of either the fields or the args. The value of each field/arg is passed into the validator function, which raises a I'm curious if anyone else has a need for something like this, and if a contribution back makes sense? I also don't know if here is the right place to post on it, so let me know if I should redirect elsewhere :). |
Hi all, The default value for the |
Hi all, from typing import Optional from pydantic import BaseModel, validate_arguments class User(BaseModel):
User.update_forward_refs() |
Re: I'm not exactly sure how to phrase this feedback yet, but would like to share some thoughts. Perhaps this minimal-ish repro case is a start:
|
@jayaddison I think you're looking for the smart_union config option here: import pydantic
@pydantic.validate_arguments(config={"smart_union": True})
def foo(a: float | int):
print(a) foo(1)
1 I've run into the same thing and stumbled upon |
Perfect - thanks, @the-matt-morris - adding And now I've read that there's a possibility that |
Is Running this from dataclasses import dataclass
from pydantic import validate_arguments, BaseModel
@validate_arguments
@dataclass
class TestyClass:
'''Section "F2 - Processing parameters"
which isn't referenced in format.temp
'''
stringy: str
inty: int
floaty: float
@classmethod
def from_dict(cls, d):
return cls(
stringy=d['s'],
inty=d['i'],
floaty=d['f']
)
TestyClass.from_dict({'s':'piff', 'i': 1, 'f': 2}) throws
|
@jnj16180340
Also, it seems to work properly if you put @classmethod
@validate_arguments
def from_dict(cls, d):
return cls(
stringy=d['s'],
inty=d['i'],
floaty=d['f']
) (It does seem unfortunate that you can't put it outside/"above" the |
This may be scope change, but I'd love to at least hear your thinking on this. Function signatures (optionally) contain one more type annotation that For example:
This currently returns I wrote an implementation of this before I found |
Update: I see that you CAN now validate return values in v2! Huzzah! |
Closing this as we have no plans to make further big changes, if you want specific things, please create a new issue. |
Future improvements to the
validate_assignment
decorator #1179:BaseModel
dataclasses
parse_obj_as
validate_arguments
TypeError
as other argument errors do. (Currently the normalValidationError
is raised which inherits fromValueError
)validate_assignment
to be set in "strict" mode so types are not coerced, this is really just Strict configuration #1098The text was updated successfully, but these errors were encountered: