Search code examples
pythonpydantic

Pass argument that is BaseModel class or Null - everything else shouldn't work


I have to pass an argument to the method, but it is not required. If it is given, is should only be accepted as a BaseModel class. Any idea how to do it?

Definition of the method:

def create_upr(args: Args, extra_args: ExtraArgs):

Definition of the class:

class ExtraArgs(BaseModel):

    polynomials: List[PolynomialInput]
    one_cutoffs: List[OneCutoffInput]
    two_cutoffs: List[TwoCutoffsInput]
    three_cutoffs: List[ThreeCutoffsInput]
    grouping_parameters: Dict[Set[str]] #grouping values in parameters to group by


class Args(BaseModel):

    gwp: float
    cover_start_date: datetime.date
    cover_end_date: datetime.date
    calculation_date: datetime.date
    calculation_method: CalculationMethod

Solution

  • Hi

    You need to verify/check if the given argument an instance of BaseModel, you can use isinstance method.

    isinstance

    then you can raise an error for example or return with a specif value from that function

    There is an example with your function:

    def create_upr(args: Args, extra_args: ExtraArgs):
       if extra_args and not isinstance(extra_args, ExtraArgs):
          raise TypeError("extra_args must be of type ExtraArgs")