How can I use field on dataclasses or pydantic.BaseModel?
It's my first time using mypyc, I think it's an amazing project with a lot of potential, and I want to use it to compile one of my project, but it is heavily dependent on the use of the Field of Pydantic, and I have not been able to figure out the way to use it without breaking the code. I get errors like the type is not inferred correctly. Is the Field not a completely supported functionality yet? Or am I doing something wrong? You can find attached an example that recreates the problem:
Environment
-
Python:
3.13.5 -
OS:
Windows 11 -
mypy:
1.17.1 -
mypyc:
0.0.1 -
pydantic:
2.11.7 -
setuptools:
80.9.0
Setup
from mypyc.build import mypycify
from setuptools import setup
# Run this to compile and test: python mypyc_setup.py build_ext --inplace
setup(
name="mypyc_output",
ext_modules=mypycify(
["src/mypyc_testing/test_compilation.py"],
opt_level="3",
debug_level="1",
strict_dunder_typing=True,
),
)
Compiled code
If I remove the Optional, it works well, if I add a type hint like int | None, it fails, if I remove the use of the Annotated, it fails at compilation time because it can not assign Field to an int attribute. I included this code on a package called mypyc_testing on a script called test_compilation.py
from pydantic.main import BaseModel
from pydantic.fields import Field
from dataclasses import dataclass, field
from typing import Annotated, Optional
class A(BaseModel):
a: Annotated[Optional[int], Field(default=-1, description="ID")]
@dataclass
class B:
a: Annotated[Optional[int], field(default=-1, metadata={"description": "ID"})]
Executable code
from mypyc_testing.test_compilation import A, B
from pydantic import ValidationError
try:
A()
except ValidationError as e:
print(e)
try:
B()
except TypeError as e:
print(e)
Errors
1 validation error for A
a
Field required [type=missing, input_value={}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.11/v/missing
B.__init__() missing 1 required positional argument: 'a'