24

Below DataFrame of pandas is not validated by pydantic. How to handle this?

from pydantic.dataclasses import dataclass

@dataclass
class DataFrames:
    dataframe1: pd.DataFrame = None
    dataframe2: pd.DataFrame = None

This throws the following error:

File "pydantic\validators.py", line 715, in find_validators

RuntimeError: no validator found for <class 'pandas.core.frame.DataFrame'>, see `arbitrary_types_allowed` in Config
Vaibhav Hiwase
  • 411
  • 1
  • 3
  • 7

4 Answers4

51

Personally, I'd mistyped the type annotation

class Foo(BaseModel):
    bar = Optional[NonNegativeInt]

Rather than;

class Foo(BaseModel):
    bar: Optional[NonNegativeInt]

Silly one ik, but double check that :)

karuhanga
  • 3,010
  • 1
  • 27
  • 30
19

According to the Pydantic Docs, you can solve your problems in several ways.

The simplest one is simply to allow arbitrary types in the model config, but this is functionality packaged with the BaseModel : quoting the docs again :

Keep in mind that pydantic.dataclasses.dataclass is a drop-in replacement for dataclasses.dataclass with validation, not a replacement for pydantic.BaseModel

With that in mind, the following code runs fine :

import pandas as pd
from pydantic import BaseModel

class DataFrames(BaseModel):
    dataframe1: pd.DataFrame = None
    dataframe2: pd.DataFrame = None

    class Config:
        arbitrary_types_allowed = True
pjmv
  • 455
  • 2
  • 9
17

If you came here with general problem no validator found for <class 'XYZ'> you should check missed BaseModel inheritance:

from pydantic import BaseModel

class MyCustomType: # We forgot inheritance here, should be MyCustomType(BaseModel)
    id: int
    text: str

class MyCustomClass2(BaseModel):
    data: List[MyCustomType]
paveldroo
  • 828
  • 9
  • 14
-1

Another possible mistake: Forgetting to inherit the model from BaseModel, so this:

class Foo():
  bar: str

instead of this:

class Foo(BaseModel):
  bar: str
jamix
  • 5,484
  • 5
  • 26
  • 35