LinkML Runtime

1.10.0 · active · verified Thu Apr 16

LinkML Runtime is the core Python runtime environment for LinkML, the Linked open data modeling language. It provides essential functionality for working with LinkML schemas, including schema loading, data validation, serialization, and deserialization. The current version is 1.10.0, and it maintains a close release cadence with the broader LinkML ecosystem, typically featuring bug fixes and enhancements aligned with LinkML core developments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a LinkML schema from a YAML string using `SchemaView`, convert a Python dictionary into a schema-compliant object using `dict_to_object`, access its attributes, and handle validation errors. It also shows how to convert an object back to a dictionary.

import os
from linkml_runtime.utils.schemaview import SchemaView
from linkml_runtime.utils.dictutils import dict_to_object, object_to_dict

# 1. Define a simple LinkML schema (YAML string)
schema_yaml = """
id: https://example.org/my_data_model
name: my_data_model
prefixes:
  ex: https://example.org/my_data_model/
default_prefix: ex

classes:
  Person:
    slots:
      - id
      - name
      - age
    required:
      - id
      - name
  
slots:
  id:
    range: string
    identifier: true
  name:
    range: string
  age:
    range: integer
    minimum_value: 0
"""

# 2. Load the schema into a SchemaView object
schema_view = SchemaView(schema_yaml)

# 3. Define a simple data instance (Python dictionary)
person_data = {
    "id": "P001",
    "name": "Alice Wonderland",
    "age": 30
}

# 4. Convert the dictionary data to a Python object based on the schema
# `dict_to_object` uses the schema definition to instantiate a Pydantic-backed object.
person_object = dict_to_object(person_data, target_class=schema_view.get_class("Person"), schemaview=schema_view)

print(f"Original dict: {person_data}")
print(f"Converted object: {person_object}")
print(f"Object ID: {person_object.id}")
print(f"Object Name: {person_object.name}")

# Demonstrate implicit validation (attempting to convert invalid data)
invalid_person_data = {
    "id": "P002",
    "name": None, # 'name' is required and cannot be None
    "age": -5     # 'age' must be non-negative
}

try:
    print("\nAttempting to convert invalid data...")
    dict_to_object(invalid_person_data, target_class=schema_view.get_class("Person"), schemaview=schema_view)
except Exception as e:
    print(f"Caught expected validation error: {e.__class__.__name__}: {e}")

# 5. Convert the object back to a dictionary
converted_back_dict = object_to_dict(person_object, schemaview=schema_view)
print(f"\nObject converted back to dict: {converted_back_dict}")

view raw JSON →