Skip to content

context

Implementation of the JSON-LD Context structure. See: http://json-ld.org/

Classes:

Attributes:

NODE_KEYS module-attribute

NODE_KEYS = {GRAPH, ID, INCLUDED, JSON, LIST, NEST, NONE, REV, SET, TYPE, VALUE, LANG}

Term module-attribute

Term = namedtuple('Term', 'id, name, type, container, index, language, reverse, context,prefix, protected')

UNDEF module-attribute

UNDEF = Defined(0)

URI_GEN_DELIMS module-attribute

URI_GEN_DELIMS = (':', '/', '?', '#', '[', ']', '@')

Context

Context(source: _ContextSourceType = None, base: Optional[str] = None, version: Optional[float] = 1.1)

Methods:

Attributes:

Source code in rdflib/plugins/shared/jsonld/context.py
def __init__(
    self,
    source: _ContextSourceType = None,
    base: Optional[str] = None,
    version: Optional[float] = 1.1,
):
    self.version: float = version or 1.1
    self.language = None
    self.vocab: Optional[str] = None
    self._base: Optional[str]
    self.base = base
    self.doc_base = base
    self.terms: Dict[str, Any] = {}
    # _alias maps NODE_KEY to list of aliases
    self._alias: Dict[str, List[str]] = {}
    self._lookup: Dict[Tuple[str, Any, Union[Defined, str], bool], Term] = {}
    self._prefixes: Dict[str, Any] = {}
    self.active = False
    self.parent: Optional[Context] = None
    self.propagate = True
    self._context_cache: Dict[str, Any] = {}
    if source:
        self.load(source)

active instance-attribute

active = False

base property writable

base: Optional[str]

doc_base instance-attribute

doc_base = base

graph_key class-attribute instance-attribute

graph_key = property(lambda self: get_key(GRAPH))

id_key class-attribute instance-attribute

id_key = property(lambda self: get_key(ID))

lang_key class-attribute instance-attribute

lang_key = property(lambda self: get_key(LANG))

language instance-attribute

language = None

list_key class-attribute instance-attribute

list_key = property(lambda self: get_key(LIST))

parent instance-attribute

parent: Optional[Context] = None

propagate instance-attribute

propagate = True

rev_key class-attribute instance-attribute

rev_key = property(lambda self: get_key(REV))

terms instance-attribute

terms: Dict[str, Any] = {}

type_key class-attribute instance-attribute

type_key = property(lambda self: get_key(TYPE))

value_key class-attribute instance-attribute

value_key = property(lambda self: get_key(VALUE))

version instance-attribute

version: float = version or 1.1

vocab instance-attribute

vocab: Optional[str] = None

add_term

add_term(name: str, idref: str, coercion: Union[Defined, str] = UNDEF, container: Union[Collection[Any], str, Defined] = UNDEF, index: Optional[Union[str, Defined]] = None, language: Optional[Union[str, Defined]] = UNDEF, reverse: bool = False, context: Any = UNDEF, prefix: Optional[bool] = None, protected: bool = False)
Source code in rdflib/plugins/shared/jsonld/context.py
def add_term(
    self,
    name: str,
    idref: str,
    coercion: Union[Defined, str] = UNDEF,
    container: Union[Collection[Any], str, Defined] = UNDEF,
    index: Optional[Union[str, Defined]] = None,
    language: Optional[Union[str, Defined]] = UNDEF,
    reverse: bool = False,
    context: Any = UNDEF,
    prefix: Optional[bool] = None,
    protected: bool = False,
):
    if self.version < 1.1 or prefix is None:
        prefix = isinstance(idref, str) and idref.endswith(URI_GEN_DELIMS)

    if not self._accept_term(name):
        return

    if self.version >= 1.1:
        existing = self.terms.get(name)
        if existing and existing.protected:
            return

    if isinstance(container, (list, set, tuple)):
        container = set(container)
    elif container is not UNDEF:
        container = set([container])
    else:
        container = set()

    term = Term(
        idref,
        name,
        coercion,
        container,
        index,
        language,
        reverse,
        context,
        prefix,
        protected,
    )

    self.terms[name] = term

    container_key: Union[Defined, str]
    for container_key in (LIST, LANG, SET):  # , INDEX, ID, GRAPH):
        if container_key in container:
            break
    else:
        container_key = UNDEF

    self._lookup[(idref, coercion or language, container_key, reverse)] = term

    if term.prefix is True:
        self._prefixes[idref] = name

expand

expand(term_curie_or_iri: Any, use_vocab: bool = True) -> Optional[str]
Source code in rdflib/plugins/shared/jsonld/context.py
def expand(self, term_curie_or_iri: Any, use_vocab: bool = True) -> Optional[str]:
    if not isinstance(term_curie_or_iri, str):
        return term_curie_or_iri

    if not self._accept_term(term_curie_or_iri):
        return ""

    if use_vocab:
        term = self.terms.get(term_curie_or_iri)
        if term:
            return term.id

    is_term, pfx, local = self._prep_expand(term_curie_or_iri)
    if pfx == "_":
        return term_curie_or_iri

    if pfx is not None:
        ns = self.terms.get(pfx)
        if ns and ns.prefix and ns.id:
            return ns.id + local
    elif is_term and use_vocab:
        if self.vocab:
            return self.vocab + term_curie_or_iri
        return None

    return self.resolve_iri(term_curie_or_iri)

find_term

find_term(idref: str, coercion: Optional[Union[str, Defined]] = None, container: Union[Defined, str] = UNDEF, language: Optional[str] = None, reverse: bool = False)
Source code in rdflib/plugins/shared/jsonld/context.py
def find_term(
    self,
    idref: str,
    coercion: Optional[Union[str, Defined]] = None,
    container: Union[Defined, str] = UNDEF,
    language: Optional[str] = None,
    reverse: bool = False,
):
    lu = self._lookup

    if coercion is None:
        coercion = language

    if coercion is not UNDEF and container:
        found = lu.get((idref, coercion, container, reverse))
        if found:
            return found

    if coercion is not UNDEF:
        found = lu.get((idref, coercion, UNDEF, reverse))
        if found:
            return found

    if container:
        found = lu.get((idref, coercion, container, reverse))
        if found:
            return found
    elif language:
        found = lu.get((idref, UNDEF, LANG, reverse))
        if found:
            return found
    else:
        found = lu.get((idref, coercion or UNDEF, SET, reverse))
        if found:
            return found

    return lu.get((idref, UNDEF, UNDEF, reverse))

get_context_for_term

get_context_for_term(term: Optional[Term]) -> Context
Source code in rdflib/plugins/shared/jsonld/context.py
def get_context_for_term(self, term: Optional[Term]) -> Context:
    if term and term.context is not UNDEF:
        return self._subcontext(term.context, propagate=True)
    return self

get_context_for_type

get_context_for_type(node: Any) -> Optional[Context]
Source code in rdflib/plugins/shared/jsonld/context.py
def get_context_for_type(self, node: Any) -> Optional[Context]:
    if self.version >= 1.1:
        rtype = self.get_type(node) if isinstance(node, dict) else None
        if not isinstance(rtype, list):
            rtype = [rtype] if rtype else []

        typeterm = None
        for rt in rtype:
            try:
                typeterm = self.terms.get(rt)
            except TypeError:
                # extra lenience, triggers if type is set to a literal
                pass
            if typeterm is not None:
                break

        if typeterm and typeterm.context:
            subcontext = self.subcontext(typeterm.context, propagate=False)
            if subcontext:
                return subcontext

    return self.parent if self.propagate is False else self

get_graph

get_graph(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_graph(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, GRAPH)

get_id

get_id(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_id(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, ID)

get_key

get_key(key: str) -> str
Source code in rdflib/plugins/shared/jsonld/context.py
def get_key(self, key: str) -> str:  # type: ignore[return]
    for alias in self.get_keys(key):
        return alias

get_keys

get_keys(key: str) -> Generator[str, None, None]
Source code in rdflib/plugins/shared/jsonld/context.py
def get_keys(self, key: str) -> Generator[str, None, None]:
    if key in self._alias:
        for alias in self._alias[key]:
            yield alias
    yield key

get_language

get_language(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_language(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, LANG)

get_list

get_list(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_list(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, LIST)

get_rev

get_rev(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_rev(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, REV)

get_set

get_set(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_set(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, SET)

get_type

get_type(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_type(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, TYPE)

get_value

get_value(obj: Dict[str, Any]) -> Any
Source code in rdflib/plugins/shared/jsonld/context.py
def get_value(self, obj: Dict[str, Any]) -> Any:
    return self._get(obj, VALUE)

isblank

isblank(ref: str) -> bool
Source code in rdflib/plugins/shared/jsonld/context.py
def isblank(self, ref: str) -> bool:
    return ref.startswith("_:")

load

load(source: _ContextSourceType, base: Optional[str] = None, referenced_contexts: Set[Any] = None)
Source code in rdflib/plugins/shared/jsonld/context.py
def load(
    self,
    source: _ContextSourceType,
    base: Optional[str] = None,
    referenced_contexts: Set[Any] = None,
):
    self.active = True
    sources: List[Tuple[Optional[str], Union[Dict[str, Any], str, None]]] = []
    # "Union[List[Union[Dict[str, Any], str]], List[Dict[str, Any]], List[str]]" : expression
    # "Union[List[Dict[str, Any]], Dict[str, Any], List[str], str]" : variable
    source = source if isinstance(source, list) else [source]
    referenced_contexts = referenced_contexts or set()
    self._prep_sources(base, source, sources, referenced_contexts)
    for source_url, source in sources:
        if source is None:
            self._clear()
        else:
            # type error: Argument 1 to "_read_source" of "Context" has incompatible type "Union[Dict[str, Any], str]"; expected "Dict[str, Any]"
            self._read_source(source, source_url, referenced_contexts)  # type: ignore[arg-type]

resolve

resolve(curie_or_iri: str) -> str
Source code in rdflib/plugins/shared/jsonld/context.py
def resolve(self, curie_or_iri: str) -> str:
    iri = self.expand(curie_or_iri, False)
    # type error: Argument 1 to "isblank" of "Context" has incompatible type "Optional[str]"; expected "str"
    if self.isblank(iri):  # type: ignore[arg-type]
        # type error: Incompatible return value type (got "Optional[str]", expected "str")
        return iri  # type: ignore[return-value]
    # type error: Unsupported right operand type for in ("Optional[str]")
    if " " in iri:  # type: ignore[operator]
        return ""
    # type error: Argument 1 to "resolve_iri" of "Context" has incompatible type "Optional[str]"; expected "str"
    return self.resolve_iri(iri)  # type: ignore[arg-type]

resolve_iri

resolve_iri(iri: str) -> str
Source code in rdflib/plugins/shared/jsonld/context.py
def resolve_iri(self, iri: str) -> str:
    # type error: Argument 1 to "norm_url" has incompatible type "Optional[str]"; expected "str"
    return norm_url(self._base, iri)  # type: ignore[arg-type]

shrink_iri

shrink_iri(iri: str) -> str
Source code in rdflib/plugins/shared/jsonld/context.py
def shrink_iri(self, iri: str) -> str:
    ns, name = split_iri(str(iri))
    pfx = self._prefixes.get(ns)
    if pfx:
        # type error: Argument 1 to "join" of "str" has incompatible type "Tuple[Any, Optional[str]]"; expected "Iterable[str]"
        return ":".join((pfx, name))  # type: ignore[arg-type]
    elif self._base:
        if str(iri) == self._base:
            return ""
        # type error: Argument 1 to "startswith" of "str" has incompatible type "Optional[str]"; expected "Union[str, Tuple[str, ...]]"
        elif iri.startswith(self._basedomain):  # type: ignore[arg-type]
            # type error: Argument 1 to "len" has incompatible type "Optional[str]"; expected "Sized"
            return iri[len(self._basedomain) :]  # type: ignore[arg-type]
    return iri

subcontext

subcontext(source: Any, propagate: bool = True) -> Context
Source code in rdflib/plugins/shared/jsonld/context.py
def subcontext(self, source: Any, propagate: bool = True) -> Context:
    # IMPROVE: to optimize, implement SubContext with parent fallback support
    parent = self.parent if self.propagate is False else self
    # type error: Item "None" of "Optional[Context]" has no attribute "_subcontext"
    return parent._subcontext(source, propagate)  # type: ignore[union-attr]

to_dict

to_dict() -> Dict[str, Any]

Returns a dictionary representation of the context that can be serialized to JSON.

Returns:

  • Dict[str, Any]

    a dictionary representation of the context.

Source code in rdflib/plugins/shared/jsonld/context.py
def to_dict(self) -> Dict[str, Any]:
    """
    Returns a dictionary representation of the context that can be
    serialized to JSON.

    Returns:
        a dictionary representation of the context.
    """
    r = {v: k for (k, v) in self._prefixes.items()}
    r.update({term.name: self._term_dict(term) for term in self._lookup.values()})
    if self.base:
        r[BASE] = self.base
    if self.language:
        r[LANG] = self.language
    return r

to_symbol

to_symbol(iri: str) -> Optional[str]
Source code in rdflib/plugins/shared/jsonld/context.py
def to_symbol(self, iri: str) -> Optional[str]:
    iri = str(iri)
    term = self.find_term(iri)
    if term:
        return term.name
    ns, name = split_iri(iri)
    if ns == self.vocab:
        return name
    pfx = self._prefixes.get(ns)
    if pfx:
        # type error: Argument 1 to "join" of "str" has incompatible type "Tuple[Any, Optional[str]]"; expected "Iterable[str]"
        return ":".join((pfx, name))  # type: ignore[arg-type]
    return iri

Defined

Bases: int