简体   繁体   中英

Is it possible to somehow initialize pydantic model without knowing the actual field names?

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM