Search code examples
pydantic

How to make all fields required in pydantic model


I have a pydantic (v2) model containing some fields with default values. I would like on some occasions for these models to be used in a "strict mode" where the default values are no longer available and every field must be supplied when using model_validate.

Is there an easy way to do this with minimal boilerplate (e.g. subclassing all the models one by one). I was hoping for maybe just an attribute to add to a model definition which would use then allow the context parameter on model_validate to be used to specify whether or not apply any default. Or maybe there is already something built into pydantic which i have missed?


Solution

  • I solved neatly by using the library https://github.com/zmievsa/cached_classproperty and the following code

    from cached_classproperty import cached_classproperty
    from pydantic import BaseModel, create_model, ConfigDict
    from pydantic_core import PydanticUndefined
    from typing import Any
    
    class StrictModel(BaseModel):
    
        model_config = ConfigDict(ignored_types=(cached_classproperty,))
    
        @cached_classproperty
        def Strict(cls, **kwargs: Any):
            m = create_model(
                cls.__name__,
                __base__ = cls
            )
    
            for field in m.model_fields.values():
                field.default = PydanticUndefined
    
            m.model_rebuild(force=True)
            
            return m
    
    ########################################################################
    
    class Foo(StrictModel):
        a: int = 2
        b: int = 2
    
    
    foo = Foo(a=1)
    print(foo) #a=1 b=2
    
    bar = Foo.Strict(a=1) #validation error as b not supplied