Skip to content

Pydantic Integration

Pydantic Logo

With typed-logic, you can use whatever framework you like to define the classes that specify predicate definitions in your theory:

  • Python dataclasses (part of the Python standard)
  • Hand-rolled classes
  • Pydantic

The only requirement is that you inherit from Fact or FactMixin, or declare your class to be a predicate definition with @predicate. For convenience, there is a ready-made base class for you to use.

However, there are some specific considerations for Pydantic due to its aversion to positional arguments.

Using the Pydantic bridge

from typedlogic.integrations.frameworks.pydantic import FactBaseModel
from pydantic import Field

class Person(FactBaseModel):
    name: str = Field(..., description="unique name of the person")
    age: int = Field(..., description="age in years", ge=0)
Person("Akira", 20)
Person(name='Akira', age=20)
from pydantic import Field, ValidationError

try:
    Person("Akira", "20 years")
except ValidationError as e:
    print("Got in error (this is expected!)")
    print(e)
Got in error (this is expected!)
1 validation error for Person
age
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='20 years', input_type=str]
    For further information visit https://errors.pydantic.dev/2.9/v/int_parsing

from utils import show
show("examples/pydantic_example.py")
from typedlogic.integrations.frameworks.pydantic import FactBaseModel
from pydantic import Field

class Person(FactBaseModel):
    name: str = Field(..., description="unique name of the person")
    age: int = Field(..., description="age in years", ge=0)
import examples.pydantic_example
from typedlogic.parsers.pyparser import PythonParser
pp = PythonParser()
theory = pp.parse(open("examples/pydantic_example.py"))
theory.predicate_definitions[0]
PredicateDefinition(predicate='FactBaseModel', arguments={}, description=None, metadata=None, parents=[], python_class=None)