Pydantic#

Example Output#

personinfo_pydantic.py

Overview#

The Pydantic Generator produces Pydantic flavored python dataclasses from a linkml model, with optional support for user-supplied jinja2 templates to generate alternate classes.

Example#

Given a definition of a Person class:

Person:
  is_a: NamedThing
  description: >-
    A person (alive, dead, undead, or fictional).
  class_uri: schema:Person
  mixins:
    - HasAliases
  slots:
    - primary_email
    - birth_date
    - age_in_years
    - gender
    - current_address
    - has_employment_history
    - has_familial_relationships
    - has_medical_history

(some details omitted for brevity, including slot definitions and parent classes)

The generate python looks like this:

class Person(NamedThing):
    """
    A person (alive, dead, undead, or fictional).
    """
    primary_email: Optional[str] = Field(None)
    birth_date: Optional[str] = Field(None)
    age_in_years: Optional[int] = Field(None, ge=0, le=999)
    gender: Optional[GenderType] = Field(None)
    current_address: Optional[Address] = Field(None, description="""The address at which a person currently lives""")
    has_employment_history: Optional[List[EmploymentEvent]] = Field(None)
    has_familial_relationships: Optional[List[FamilialRelationship]] = Field(None)
    has_medical_history: Optional[List[MedicalEvent]] = Field(None)
    aliases: Optional[List[str]] = Field(None)
    id: Optional[str] = Field(None)
    name: Optional[str] = Field(None)
    description: Optional[str] = Field(None)
    image: Optional[str] = Field(None)

Docs#

Command Line#

gen-pydantic#

Generate pydantic classes to represent a LinkML model

gen-pydantic [OPTIONS] YAMLFILE

Options

-V, --version#

Show the version and exit.

--template_file <template_file>#

Optional jinja2 template to use for class generation

-f, --format <format>#

Output format

Default:

pydantic

Options:

pydantic

--metadata, --no-metadata#

Include metadata in output

Default:

True

--useuris, --metauris#

Include metadata in output

Default:

True

-im, --importmap <importmap>#

Import mapping file

--log_level <log_level>#

Logging level

Default:

WARNING

Options:

CRITICAL | ERROR | WARNING | INFO | DEBUG

-v, --verbose#

verbosity

--mergeimports, --no-mergeimports#

Merge imports into source file (default=mergeimports)

--stacktrace, --no-stacktrace#

Print a stack trace when an error occurs

Default:

False

Arguments

YAMLFILE#

Required argument

Code#

class linkml.generators.pydanticgen.PydanticGenerator(schema: ~typing.Union[str, ~typing.TextIO, ~linkml_runtime.linkml_model.meta.SchemaDefinition, Generator], schemaview: ~typing.Optional[~linkml_runtime.utils.schemaview.SchemaView] = None, format: ~typing.Optional[str] = None, metadata: bool = <factory>, useuris: ~typing.Optional[bool] = None, log_level: int = 30, mergeimports: ~typing.Optional[bool] = <factory>, source_file_date: ~typing.Optional[str] = None, source_file_size: ~typing.Optional[int] = None, logger: ~typing.Optional[~logging.Logger] = None, verbose: ~typing.Optional[bool] = None, output: ~typing.Optional[str] = None, namespaces: ~typing.Optional[~linkml_runtime.utils.namespaces.Namespaces] = None, directory_output: bool = False, base_dir: str = None, metamodel_name_map: ~typing.Dict[str, str] = None, importmap: ~typing.Optional[~typing.Union[str, ~typing.Mapping[str, str]]] = None, emit_prefixes: ~typing.Set[str] = <factory>, metamodel: ~linkml.utils.schemaloader.SchemaLoader = None, stacktrace: bool = False, template_file: str = None, package: str = 'example', allow_extra: bool = <factory>, gen_mixin_inheritance: bool = <factory>, gen_classvars: bool = <factory>, gen_slots: bool = <factory>, genmeta: bool = <factory>, emit_metadata: bool = <factory>, **_kwargs)[source]#

Generates Pydantic-compliant classes from a schema

This is an alternative to the dataclasses-based Pythongen

serialize() str[source]#

Generate output in the required format

Parameters:

kwargs – Generater specific parameters

Returns:

Generated output

Additional Notes#

LinkML contains two Python generators. The Pydantic dataclass generator is specifically useful for FastAPI, but is newer and less full featured than the standard Python generator.