Skip to content

# `` context

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

Classes:

- `Context` –
- `Defined` –

Attributes:

- `NODE_KEYS` –
- `Term` –
- `UNDEF` –
- `URI_GEN_DELIMS` –

## `` 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:

- `add_term` –
- `expand` –
- `find_term` –
- `get_context_for_term` –
- `get_context_for_type` –
- `get_graph` –
- `get_id` –
- `get_key` –
- `get_keys` –
- `get_language` –
- `get_list` –
- `get_rev` –
- `get_set` –
- `get_type` –
- `get_value` –
- `isblank` –
- `load` –
- `resolve` –
- `resolve_iri` –
- `shrink_iri` –
- `subcontext` –
- `to_dict` –

  Returns a dictionary representation of the context that can be

- `to_symbol` –

Attributes:

- `active` –
- `base` (`Optional[str]`) –
- `doc_base` –
- `graph_key` –
- `id_key` –
- `lang_key` –
- `language` –
- `list_key` –
- `parent` (`Optional[Context]`) –
- `propagate` –
- `rev_key` –
- `terms` (`Dict[str, Any]`) –
- `type_key` –
- `value_key` –
- `version` (`float`) –
- `vocab` (`Optional[str]`) –

Source code in `rdflib/plugins/shared/jsonld/context.py`

    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96

    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`

    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280

    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`

    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364

    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`

    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318

    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`

    147
    148
    149
    150

    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`

    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173

    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`

    187
    188

    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`

    175
    176

    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`

    206
    207
    208

    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`

    210
    211
    212
    213
    214

    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`

    181
    182

    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`

    190
    191

    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`

    196
    197

    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`

    193
    194

    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`

    178
    179

    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`

    184
    185

    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`

    336
    337

    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`

    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413

    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`

    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330

    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`

    332
    333
    334

    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`

    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379

    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`

    115
    116
    117
    118
    119

    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`

    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666

    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`

    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393

    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`