Michal
Michal

Reputation: 971

Is it possible to get a dict of fields with FieldInfo from the Pydantic Dataclass?

When creating classes by inheriting from BaseModel, I can use the model_fields property to get a dict of field names, and FieldInfo, but how can I do it if I use the Pydantic Dataclass decorator instead of BaseModel?

When using BaseModel I can do this:

from pydantic import BaseModel, Field

class Person(BaseModel):
    first_name: str = Field(alias='firstName')
    age: int

p = Person(firstName='John', age=42)

p.model_fields

p.model_fields will return dict[str, FieldInfo] with all the information about fields:

{'first_name': FieldInfo(annotation=str, required=True, alias='firstName', alias_priority=2),

'age': FieldInfo(annotation=int, required=True)}

I want get same info about fields when using Pydantic's dataclasses:

from pydantic.dataclasses import dataclass
from pydantic import Field

@dataclass
class Person:
    first_name: str = Field(alias='firstName')
    age: int

p = Person(firstName='John', age=42)
# p.model_fields doesn't exists

I looked at RootModel and there's nothing, I tried TypeAdapter which has core_schema but it has different structure and no FieldInfo objects.

Is there no way to get this infro from Pydantic's dataclass?

Upvotes: 0

Views: 702

Answers (1)

Victor Egiazarian
Victor Egiazarian

Reputation: 1116

I'm not sure if this is exactly what you're looking for (at least the format is a little bit different), but I found the following way:

import dataclasses

from pydantic import Field
from pydantic.dataclasses import dataclass

@dataclass
class Item:
    value: int = Field(..., description="Description")


item = Item(value=1)
dataclasses.fields(item)

Upvotes: 0

Related Questions