Skip to content

TypeDirectedDocumentLoader

Document loader that dispatches to per-type loaders.

Constructed with a mapping from Python types to DocumentLoader instances. Dispatch uses isinstance, so a pathlib.Path registration matches pathlib.PosixPath / WindowsPath. The first matching entry in insertion order wins.

An unregistered input type raises JsonLdError with code loading document failed and details naming the registered types.

Parameters:

Name Type Description Default
loaders Mapping[type, DocumentLoader]

mapping of type to document loader.

required

TypeDirectedDocumentLoader dispatches a value to the loader registered for its Python type. Applications can register any types that represent distinct document locations or loading policies.

Example use case

One use case for TypeDirectedDocumentLoader is an application that accepts local pathlib.Path values and remote URL strings in the same JSON-LD workflow. This example routes paths through FileDocumentLoader; when a local document references a remote @context, its str URL is delegated to SchemeDirectedDocumentLoader.

Example type_directed.py

import json
from pathlib import Path

from pyld import (
    FileDocumentLoader,
    FrozenDocumentLoader,
    SchemeDirectedDocumentLoader,
    TypeDirectedDocumentLoader,
    jsonld,
)

person = (
    Path(__file__).resolve().parent.parent / 'data' / 'person_remote_context.jsonld'
)

file_loader = FileDocumentLoader()
http_loader = FrozenDocumentLoader(
    documents={
        'https://example.com/context': {
            '@context': {'name': 'http://schema.org/name'},
        },
    }
)
loader = TypeDirectedDocumentLoader(
    {
        Path: file_loader,
        str: SchemeDirectedDocumentLoader(
            file=file_loader,
            http=http_loader,
            https=http_loader,
        ),
    }
)
remote = jsonld.load_document(person, options={'documentLoader': loader})
result = jsonld.expand(
    remote['document'],
    options={
        'documentLoader': loader,
        'base': remote['documentUrl'],
    },
)
print(json.dumps(result, indent=2))
Output
[
  {
    "http://schema.org/name": [
      {
        "@value": "Ada Lovelace"
      }
    ]
  }
]

Source person_remote_context.jsonld

{
  "@context": "https://example.com/context",
  "name": "Ada Lovelace"
}