Reputation: 633
I am trying to create some kind of dynamic validation of input-output of a function:
from pydantic import ValidationError, BaseModel
import numpy as np
class ValidationImage:
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
if not isinstance(v, np.ndarray):
raise TypeError("np.ndarray required")
return v
class TestModel(BaseModel):
image: ValidationImage
def validate(msg, model):
try:
message = model(image=msg)
except ValidationError as e:
return e
testimg = np.zeros([0])
print(validate(testimg, TestModel))
But the problem is that at this point message = model(image=msg)
I actually do need to know that there is image
field inside the model that I got as an argument of validate
function.
I want to somehow create a model instance without knowing the actual field names(from list maybe?)
I tried message = model(msg)
- doesn't work. I want to know if it's possible to do it? Or are there any workarounds?
UPDATE #1:
I was able to get field name by using list(model.__fields__.keys())[0]
But I don't know how to use str
as actual code. And it seems kinda like a bad practice
Upvotes: 2
Views: 1942
Reputation: 4411
I think you want to use argument expansion here:
def validate(args, model):
# `args` must be a dict with str keys.
try:
message = model(**args)
except ValidationError as e:
return e
testimg = np.zeros([0])
print(validate({"image": testimg}, TestModel))
You can get even fancier using kwargs
:
def validate(model, **kwargs):
try:
message = model(**kwargs)
except ValidationError as e:
return e
testimg = np.zeros([0])
print(validate(TestModel, image=testimg))
Upvotes: 1