Source code

Download source archive ↓

src/rdflib/plugins/stores/memory.py

1#
2#
3from __future__ import annotations
4
5from typing import (
6    TYPE_CHECKING,
7    Any,
8    Collection,
9    Dict,
10    Generator,
11    Iterator,
12    Mapping,
13    Optional,
14    Set,
15    Tuple,
16    Union,
17    overload,
18)
19
20from rdflib.store import Store
21from rdflib.util import _coalesce
22
23if TYPE_CHECKING:
24    from rdflib.graph import (
25        Graph,
26        _ContextType,
27        _ObjectType,
28        _PredicateType,
29        _SubjectType,
30        _TriplePatternType,
31        _TripleType,
32    )
33    from rdflib.plugins.sparql.sparql import Query, Update
34    from rdflib.query import Result
35    from rdflib.term import Identifier, URIRef
36
37__all__ = ["SimpleMemory", "Memory"]
38
39ANY: None = None
40
41
42class SimpleMemory(Store):
43    """A fast naive in memory implementation of a triple store.
44
45    This triple store uses nested dictionaries to store triples. Each
46    triple is stored in two such indices as follows `spo[s][p][o]` = 1 and
47    `pos[p][o][s]` = 1.
48
49    Authors: Michel Pelletier, Daniel Krech, Stefan Niederhauser
50    """
51
52    def __init__(
53        self,
54        configuration: Optional[str] = None,
55        identifier: Optional[Identifier] = None,
56    ):
57        super(SimpleMemory, self).__init__(configuration)
58        self.identifier = identifier
59
60        # indexed by [subject][predicate][object]
61        self.__spo: Dict[_SubjectType, Dict[_PredicateType, Dict[_ObjectType, int]]] = (
62            {}
63        )
64
65        # indexed by [predicate][object][subject]
66        self.__pos: Dict[_PredicateType, Dict[_ObjectType, Dict[_SubjectType, int]]] = (
67            {}
68        )
69
70        # indexed by [predicate][object][subject]
71        self.__osp: Dict[_ObjectType, Dict[_SubjectType, Dict[_PredicateType, int]]] = (
72            {}
73        )
74
75        self.__namespace: Dict[str, URIRef] = {}
76        self.__prefix: Dict[URIRef, str] = {}
77
78    def add(
79        self,
80        triple: _TripleType,
81        context: _ContextType,
82        quoted: bool = False,
83    ) -> None:
84        """Add a triple to the store of triples."""
85        # add dictionary entries for spo[s][p][p] = 1 and pos[p][o][s]
86        # = 1, creating the nested dictionaries where they do not yet
87        # exits.
88        subject, predicate, object = triple
89        spo = self.__spo
90        try:
91            po = spo[subject]
92        except:  # noqa: E722
93            po = spo[subject] = {}
94        try:
95            o = po[predicate]
96        except:  # noqa: E722
97            o = po[predicate] = {}
98        o[object] = 1
99
100        pos = self.__pos
101        try:
102            os = pos[predicate]
103        except:  # noqa: E722
104            os = pos[predicate] = {}
105        try:
106            s = os[object]
107        except:  # noqa: E722
108            s = os[object] = {}
109        s[subject] = 1
110
111        osp = self.__osp
112        try:
113            sp = osp[object]
114        except:  # noqa: E722
115            sp = osp[object] = {}
116        try:
117            p = sp[subject]
118        except:  # noqa: E722
119            p = sp[subject] = {}
120        p[predicate] = 1
121
122    def remove(
123        self,
124        triple_pattern: _TriplePatternType,
125        context: Optional[_ContextType] = None,
126    ) -> None:
127        for (subject, predicate, object), c in list(self.triples(triple_pattern)):
128            del self.__spo[subject][predicate][object]
129            del self.__pos[predicate][object][subject]
130            del self.__osp[object][subject][predicate]
131
132    def triples(
133        self,
134        triple_pattern: _TriplePatternType,
135        context: Optional[_ContextType] = None,
136    ) -> Iterator[Tuple[_TripleType, Iterator[Optional[_ContextType]]]]:
137        """A generator over all the triples matching"""
138        subject, predicate, object = triple_pattern
139        if subject != ANY:  # subject is given
140            spo = self.__spo
141            if subject in spo:
142                subjectDictionary = spo[subject]  # noqa: N806
143                if predicate != ANY:  # subject+predicate is given
144                    if predicate in subjectDictionary:
145                        if object != ANY:  # subject+predicate+object is given
146                            if object in subjectDictionary[predicate]:
147                                yield (subject, predicate, object), self.__contexts()
148                            else:  # given object not found
149                                pass
150                        else:  # subject+predicate is given, object unbound
151                            for o in subjectDictionary[predicate].keys():
152                                yield (subject, predicate, o), self.__contexts()
153                    else:  # given predicate not found
154                        pass
155                else:  # subject given, predicate unbound
156                    for p in subjectDictionary.keys():
157                        if object != ANY:  # object is given
158                            if object in subjectDictionary[p]:
159                                yield (subject, p, object), self.__contexts()
160                            else:  # given object not found
161                                pass
162                        else:  # object unbound
163                            for o in subjectDictionary[p].keys():
164                                yield (subject, p, o), self.__contexts()
165            else:  # given subject not found
166                pass
167        elif predicate != ANY:  # predicate is given, subject unbound
168            pos = self.__pos
169            if predicate in pos:
170                predicateDictionary = pos[predicate]  # noqa: N806
171                if object != ANY:  # predicate+object is given, subject unbound
172                    if object in predicateDictionary:
173                        for s in predicateDictionary[object].keys():
174                            yield (s, predicate, object), self.__contexts()
175                    else:  # given object not found
176                        pass
177                else:  # predicate is given, object+subject unbound
178                    for o in predicateDictionary.keys():
179                        for s in predicateDictionary[o].keys():
180                            yield (s, predicate, o), self.__contexts()
181        elif object != ANY:  # object is given, subject+predicate unbound
182            osp = self.__osp
183            if object in osp:
184                objectDictionary = osp[object]  # noqa: N806
185                for s in objectDictionary.keys():
186                    for p in objectDictionary[s].keys():
187                        yield (s, p, object), self.__contexts()
188        else:  # subject+predicate+object unbound
189            spo = self.__spo
190            for s in spo.keys():
191                subjectDictionary = spo[s]  # noqa: N806
192                for p in subjectDictionary.keys():
193                    for o in subjectDictionary[p].keys():
194                        yield (s, p, o), self.__contexts()
195
196    def __len__(self, context: Optional[_ContextType] = None) -> int:
197        # @@ optimize
198        i = 0
199        for triple in self.triples((None, None, None)):
200            i += 1
201        return i
202
203    def bind(self, prefix: str, namespace: URIRef, override: bool = True) -> None:
204        # should be identical to `Memory.bind`
205        bound_namespace = self.__namespace.get(prefix)
206        bound_prefix = _coalesce(
207            self.__prefix.get(namespace),
208            # type error: error: Argument 1 to "get" of "Mapping" has incompatible type "Optional[URIRef]"; expected "URIRef"
209            self.__prefix.get(bound_namespace),  # type: ignore[arg-type]
210        )
211        if override:
212            if bound_prefix is not None:
213                del self.__namespace[bound_prefix]
214            if bound_namespace is not None:
215                del self.__prefix[bound_namespace]
216            self.__prefix[namespace] = prefix
217            self.__namespace[prefix] = namespace
218        else:
219            # type error: Invalid index type "Optional[URIRef]" for "Dict[URIRef, str]"; expected type "URIRef"
220            self.__prefix[_coalesce(bound_namespace, namespace)] = _coalesce(  # type: ignore[index]
221                bound_prefix, default=prefix
222            )
223            # type error: Invalid index type "Optional[str]" for "Dict[str, URIRef]"; expected type "str"
224            self.__namespace[_coalesce(bound_prefix, prefix)] = _coalesce(  # type: ignore[index]
225                bound_namespace, default=namespace
226            )
227
228    def namespace(self, prefix: str) -> Optional[URIRef]:
229        return self.__namespace.get(prefix, None)
230
231    def prefix(self, namespace: URIRef) -> Optional[str]:
232        return self.__prefix.get(namespace, None)
233
234    def namespaces(self) -> Iterator[Tuple[str, URIRef]]:
235        for prefix, namespace in self.__namespace.items():
236            yield prefix, namespace
237
238    def __contexts(self) -> Generator[_ContextType, None, None]:
239        # TODO: best way to return empty generator
240        # type error: Need type annotation for "c"
241        return (c for c in [])  # type: ignore[var-annotated]
242
243    # type error: Missing return statement
244    def query(  # type: ignore[return]
245        self,
246        query: Union[Query, str],
247        initNs: Mapping[str, Any],  # noqa: N803
248        initBindings: Mapping[str, Identifier],  # noqa: N803
249        queryGraph: str,  # noqa: N803
250        **kwargs: Any,
251    ) -> Result:
252        super(SimpleMemory, self).query(
253            query, initNs, initBindings, queryGraph, **kwargs
254        )
255
256    def update(
257        self,
258        update: Union[Update, str],
259        initNs: Mapping[str, Any],  # noqa: N803
260        initBindings: Mapping[str, Identifier],  # noqa: N803
261        queryGraph: str,  # noqa: N803
262        **kwargs: Any,
263    ) -> None:
264        super(SimpleMemory, self).update(
265            update, initNs, initBindings, queryGraph, **kwargs
266        )
267
268
269class Memory(Store):
270    """An in memory implementation of a triple store.
271
272    Same as SimpleMemory above, but is Context-aware, Graph-aware, and Formula-aware
273    Authors: Ashley Sommer
274    """
275
276    context_aware = True
277    formula_aware = True
278    graph_aware = True
279
280    def __init__(
281        self,
282        configuration: Optional[str] = None,
283        identifier: Optional[Identifier] = None,
284    ):
285        super(Memory, self).__init__(configuration)
286        self.identifier = identifier
287
288        # indexed by [subject][predicate][object]
289        self.__spo: Dict[_SubjectType, Dict[_PredicateType, Dict[_ObjectType, int]]] = (
290            {}
291        )
292
293        # indexed by [predicate][object][subject]
294        self.__pos: Dict[_PredicateType, Dict[_ObjectType, Dict[_SubjectType, int]]] = (
295            {}
296        )
297
298        # indexed by [predicate][object][subject]
299        self.__osp: Dict[_ObjectType, Dict[_SubjectType, Dict[_PredicateType, int]]] = (
300            {}
301        )
302
303        self.__namespace: Dict[str, URIRef] = {}
304        self.__prefix: Dict[URIRef, str] = {}
305        self.__context_obj_map: Dict[str, Graph] = {}
306        self.__tripleContexts: Dict[_TripleType, Dict[Optional[str], bool]] = {}
307        self.__contextTriples: Dict[Optional[str], Set[_TripleType]] = {None: set()}
308        # all contexts used in store (unencoded)
309        self.__all_contexts: Set[Graph] = set()
310        # default context information for triples
311        self.__defaultContexts: Optional[Dict[Optional[str], bool]] = None
312
313    def add(
314        self,
315        triple: _TripleType,
316        context: _ContextType,
317        quoted: bool = False,
318    ) -> None:
319        """Add a triple to the store of triples."""
320        # add dictionary entries for spo[s][p][p] = 1 and pos[p][o][s]
321        # = 1, creating the nested dictionaries where they do not yet
322        # exits.
323        Store.add(self, triple, context, quoted=quoted)
324        if context is not None:
325            self.__all_contexts.add(context)
326        subject, predicate, object_ = triple
327
328        spo = self.__spo
329        try:
330            po = spo[subject]
331        except LookupError:
332            po = spo[subject] = {}
333        try:
334            o = po[predicate]
335        except LookupError:
336            o = po[predicate] = {}
337
338        try:
339            _ = o[object_]
340            # This cannot be reached if (s, p, o) was not inserted before.
341            triple_exists = True
342        except KeyError:
343            o[object_] = 1
344            triple_exists = False
345        self.__add_triple_context(triple, triple_exists, context, quoted)
346
347        if triple_exists:
348            # No need to insert twice this triple.
349            return
350
351        pos = self.__pos
352        try:
353            os = pos[predicate]
354        except LookupError:
355            os = pos[predicate] = {}
356        try:
357            s = os[object_]
358        except LookupError:
359            s = os[object_] = {}
360        s[subject] = 1
361
362        osp = self.__osp
363        try:
364            sp = osp[object_]
365        except LookupError:
366            sp = osp[object_] = {}
367        try:
368            p = sp[subject]
369        except LookupError:
370            p = sp[subject] = {}
371        p[predicate] = 1
372
373    def remove(
374        self,
375        triple_pattern: _TriplePatternType,
376        context: Optional[_ContextType] = None,
377    ) -> None:
378        req_ctx = self.__ctx_to_str(context)
379        for triple, c in self.triples(triple_pattern, context=context):
380            subject, predicate, object_ = triple
381            for ctx in self.__get_context_for_triple(triple):
382                if context is not None and req_ctx != ctx:
383                    continue
384                self.__remove_triple_context(triple, ctx)
385            ctxs = self.__get_context_for_triple(triple, skipQuoted=True)
386            if None in ctxs and (context is None or len(ctxs) == 1):
387                # remove from default graph too
388                self.__remove_triple_context(triple, None)
389            if len(self.__get_context_for_triple(triple)) == 0:
390                del self.__spo[subject][predicate][object_]
391                del self.__pos[predicate][object_][subject]
392                del self.__osp[object_][subject][predicate]
393                del self.__tripleContexts[triple]
394        if (
395            req_ctx is not None
396            and req_ctx in self.__contextTriples
397            and len(self.__contextTriples[req_ctx]) == 0
398        ):
399            # all triples are removed out of this context
400            # and it's not the default context so delete it
401            del self.__contextTriples[req_ctx]
402
403        if (
404            triple_pattern == (None, None, None)
405            and context in self.__all_contexts
406            and not self.graph_aware
407        ):
408            # remove the whole context
409            self.__all_contexts.remove(context)
410
411    def triples(
412        self,
413        triple_pattern: _TriplePatternType,
414        context: Optional[_ContextType] = None,
415    ) -> Generator[
416        Tuple[_TripleType, Generator[Optional[_ContextType], None, None]],
417        None,
418        None,
419    ]:
420        """A generator over all the triples matching"""
421        req_ctx = self.__ctx_to_str(context)
422        subject, predicate, object_ = triple_pattern
423
424        # all triples case (no triple parts given as pattern)
425        if subject is None and predicate is None and object_ is None:
426            # Just dump all known triples from the given graph
427            if req_ctx not in self.__contextTriples:
428                return
429            for triple in self.__contextTriples[req_ctx].copy():
430                yield triple, self.__contexts(triple)
431
432        # optimize "triple in graph" case (all parts given)
433        elif subject is not None and predicate is not None and object_ is not None:
434            # type error: Incompatible types in assignment (expression has type "Tuple[Optional[IdentifiedNode], Optional[IdentifiedNode], Optional[Identifier]]", variable has type "Tuple[IdentifiedNode, IdentifiedNode, Identifier]")
435            # NOTE on type error: at this point, all elements of triple_pattern
436            # is not None, so it has the same type as triple
437            triple = triple_pattern  # type: ignore[assignment]
438            try:
439                _ = self.__spo[subject][predicate][object_]
440                if self.__triple_has_context(triple, req_ctx):
441                    yield triple, self.__contexts(triple)
442            except KeyError:
443                return
444
445        elif subject is not None:  # subject is given
446            spo = self.__spo
447            if subject in spo:
448                subjectDictionary = spo[subject]  # noqa: N806
449                if predicate is not None:  # subject+predicate is given
450                    if predicate in subjectDictionary:
451                        if object_ is not None:  # subject+predicate+object is given
452                            if object_ in subjectDictionary[predicate]:
453                                triple = (subject, predicate, object_)
454                                if self.__triple_has_context(triple, req_ctx):
455                                    yield triple, self.__contexts(triple)
456                            else:  # given object not found
457                                pass
458                        else:  # subject+predicate is given, object unbound
459                            for o in list(subjectDictionary[predicate].keys()):
460                                triple = (subject, predicate, o)
461                                if self.__triple_has_context(triple, req_ctx):
462                                    yield triple, self.__contexts(triple)
463                    else:  # given predicate not found
464                        pass
465                else:  # subject given, predicate unbound
466                    for p in list(subjectDictionary.keys()):
467                        if object_ is not None:  # object is given
468                            if object_ in subjectDictionary[p]:
469                                triple = (subject, p, object_)
470                                if self.__triple_has_context(triple, req_ctx):
471                                    yield triple, self.__contexts(triple)
472                            else:  # given object not found
473                                pass
474                        else:  # object unbound
475                            for o in list(subjectDictionary[p].keys()):
476                                triple = (subject, p, o)
477                                if self.__triple_has_context(triple, req_ctx):
478                                    yield triple, self.__contexts(triple)
479            else:  # given subject not found
480                pass
481        elif predicate is not None:  # predicate is given, subject unbound
482            pos = self.__pos
483            if predicate in pos:
484                predicateDictionary = pos[predicate]  # noqa: N806
485                if object_ is not None:  # predicate+object is given, subject unbound
486                    if object_ in predicateDictionary:
487                        for s in list(predicateDictionary[object_].keys()):
488                            triple = (s, predicate, object_)
489                            if self.__triple_has_context(triple, req_ctx):
490                                yield triple, self.__contexts(triple)
491                    else:  # given object not found
492                        pass
493                else:  # predicate is given, object+subject unbound
494                    for o in list(predicateDictionary.keys()):
495                        for s in list(predicateDictionary[o].keys()):
496                            triple = (s, predicate, o)
497                            if self.__triple_has_context(triple, req_ctx):
498                                yield triple, self.__contexts(triple)
499        elif object_ is not None:  # object is given, subject+predicate unbound
500            osp = self.__osp
501            if object_ in osp:
502                objectDictionary = osp[object_]  # noqa: N806
503                for s in list(objectDictionary.keys()):
504                    for p in list(objectDictionary[s].keys()):
505                        triple = (s, p, object_)
506                        if self.__triple_has_context(triple, req_ctx):
507                            yield triple, self.__contexts(triple)
508        else:  # subject+predicate+object unbound
509            # Shouldn't get here if all other cases above worked correctly.
510            spo = self.__spo
511            for s in list(spo.keys()):
512                subjectDictionary = spo[s]  # noqa: N806
513                for p in list(subjectDictionary.keys()):
514                    for o in list(subjectDictionary[p].keys()):
515                        triple = (s, p, o)
516                        if self.__triple_has_context(triple, req_ctx):
517                            yield triple, self.__contexts(triple)
518
519    def bind(self, prefix: str, namespace: URIRef, override: bool = True) -> None:
520        # should be identical to `SimpleMemory.bind`
521        bound_namespace = self.__namespace.get(prefix)
522        bound_prefix = _coalesce(
523            self.__prefix.get(namespace),
524            # type error: error: Argument 1 to "get" of "Mapping" has incompatible type "Optional[URIRef]"; expected "URIRef"
525            self.__prefix.get(bound_namespace),  # type: ignore[arg-type]
526        )
527        if override:
528            if bound_prefix is not None:
529                del self.__namespace[bound_prefix]
530            if bound_namespace is not None:
531                del self.__prefix[bound_namespace]
532            self.__prefix[namespace] = prefix
533            self.__namespace[prefix] = namespace
534        else:
535            # type error: Invalid index type "Optional[URIRef]" for "Dict[URIRef, str]"; expected type "URIRef"
536            self.__prefix[_coalesce(bound_namespace, namespace)] = _coalesce(  # type: ignore[index]
537                bound_prefix, default=prefix
538            )
539            # type error: Invalid index type "Optional[str]" for "Dict[str, URIRef]"; expected type "str"
540            # type error: Incompatible types in assignment (expression has type "Optional[URIRef]", target has type "URIRef")
541            self.__namespace[_coalesce(bound_prefix, prefix)] = _coalesce(  # type: ignore[index]
542                bound_namespace, default=namespace
543            )
544
545    def namespace(self, prefix: str) -> Optional[URIRef]:
546        return self.__namespace.get(prefix, None)
547
548    def prefix(self, namespace: URIRef) -> Optional[str]:
549        return self.__prefix.get(namespace, None)
550
551    def namespaces(self) -> Iterator[Tuple[str, URIRef]]:
552        for prefix, namespace in self.__namespace.items():
553            yield prefix, namespace
554
555    def contexts(
556        self, triple: Optional[_TripleType] = None
557    ) -> Generator[_ContextType, None, None]:
558        if triple is None or triple == (None, None, None):
559            return (context for context in list(self.__all_contexts))
560
561        subj, pred, obj = triple
562        try:
563            _ = self.__spo[subj][pred][obj]
564            return self.__contexts(triple)
565        except KeyError:
566            return (_ for _ in [])
567
568    def __len__(self, context: Optional[_ContextType] = None) -> int:
569        ctx = self.__ctx_to_str(context)
570        if ctx not in self.__contextTriples:
571            return 0
572        return len(self.__contextTriples[ctx])
573
574    def add_graph(self, graph: Graph) -> None:
575        if not self.graph_aware:
576            Store.add_graph(self, graph)
577        else:
578            self.__all_contexts.add(graph)
579
580    def remove_graph(self, graph: Graph) -> None:
581        if not self.graph_aware:
582            Store.remove_graph(self, graph)
583        else:
584            self.remove((None, None, None), graph)
585            try:
586                self.__all_contexts.remove(graph)
587            except KeyError:
588                pass  # we didn't know this graph, no problem
589
590    # internal utility methods below
591    def __add_triple_context(
592        self,
593        triple: _TripleType,
594        triple_exists: bool,
595        context: Optional[_ContextType],
596        quoted: bool,
597    ) -> None:
598        """add the given context to the set of contexts for the triple"""
599        ctx = self.__ctx_to_str(context)
600        quoted = bool(quoted)
601        if triple_exists:
602            # we know the triple exists somewhere in the store
603            try:
604                triple_context = self.__tripleContexts[triple]
605            except KeyError:
606                # triple exists with default ctx info
607                # start with a copy of the default ctx info
608                # type error: Item "None" of "Optional[Dict[Optional[str], bool]]" has no attribute "copy"
609                triple_context = self.__tripleContexts[triple] = (
610                    self.__defaultContexts.copy()  # type: ignore[union-attr]
611                )
612
613            triple_context[ctx] = quoted
614
615            if not quoted:
616                triple_context[None] = quoted
617
618        else:
619            # the triple didn't exist before in the store
620            if quoted:  # this context only
621                triple_context = self.__tripleContexts[triple] = {ctx: quoted}
622            else:  # default context as well
623                triple_context = self.__tripleContexts[triple] = {
624                    ctx: quoted,
625                    None: quoted,
626                }
627
628        # if the triple is not quoted add it to the default context
629        if not quoted:
630            self.__contextTriples[None].add(triple)
631
632        # always add the triple to given context, making sure it's initialized
633        if ctx not in self.__contextTriples:
634            self.__contextTriples[ctx] = set()
635        self.__contextTriples[ctx].add(triple)
636
637        # if this is the first ever triple in the store, set default ctx info
638        if self.__defaultContexts is None:
639            self.__defaultContexts = triple_context
640        # if the context info is the same as default, no need to store it
641        if triple_context == self.__defaultContexts:
642            del self.__tripleContexts[triple]
643
644    def __get_context_for_triple(
645        self, triple: _TripleType, skipQuoted: bool = False  # noqa: N803
646    ) -> Collection[Optional[str]]:
647        """return a list of contexts (str) for the triple, skipping
648        quoted contexts if skipQuoted==True"""
649
650        ctxs = self.__tripleContexts.get(triple, self.__defaultContexts)
651
652        if not skipQuoted:
653            # type error: Item "None" of "Optional[Dict[Optional[str], bool]]" has no attribute "keys"
654            return ctxs.keys()  # type: ignore[union-attr]
655
656        # type error: Item "None" of "Optional[Dict[Optional[str], bool]]" has no attribute "items"
657        return [ctx for ctx, quoted in ctxs.items() if not quoted]  # type: ignore[union-attr]
658
659    def __triple_has_context(self, triple: _TripleType, ctx: Optional[str]) -> bool:
660        """return True if the triple exists in the given context"""
661        # type error: Unsupported right operand type for in ("Optional[Dict[Optional[str], bool]]")
662        return ctx in self.__tripleContexts.get(triple, self.__defaultContexts)  # type: ignore[operator]
663
664    def __remove_triple_context(self, triple: _TripleType, ctx):
665        """remove the context from the triple"""
666        # type error: Item "None" of "Optional[Dict[Optional[str], bool]]" has no attribute "copy"
667        ctxs = self.__tripleContexts.get(triple, self.__defaultContexts).copy()  # type: ignore[union-attr]
668        del ctxs[ctx]
669        if ctxs == self.__defaultContexts:
670            del self.__tripleContexts[triple]
671        else:
672            self.__tripleContexts[triple] = ctxs
673        self.__contextTriples[ctx].remove(triple)
674
675    @overload
676    def __ctx_to_str(self, ctx: _ContextType) -> str: ...
677
678    @overload
679    def __ctx_to_str(self, ctx: None) -> None: ...
680
681    def __ctx_to_str(self, ctx: Optional[_ContextType]) -> Optional[str]:
682        if ctx is None:
683            return None
684        try:
685            # ctx could be a graph. In that case, use its identifier
686            ctx_str = "{}:{}".format(ctx.identifier.__class__.__name__, ctx.identifier)
687            self.__context_obj_map[ctx_str] = ctx
688            return ctx_str
689        except AttributeError:
690            # otherwise, ctx should be a URIRef or BNode or str
691            # NOTE on type errors: This is actually never called with ctx value as str in all unit tests, so this seems like it should just not be here.
692            # type error: Subclass of "Graph" and "str" cannot exist: would have incompatible method signatures
693            if isinstance(ctx, str):  # type: ignore[unreachable]
694                # type error: Statement is unreachable
695                ctx_str = "{}:{}".format(ctx.__class__.__name__, ctx)  # type: ignore[unreachable]
696                if ctx_str in self.__context_obj_map:
697                    return ctx_str
698                self.__context_obj_map[ctx_str] = ctx
699                return ctx_str
700            raise RuntimeError("Cannot use that type of object as a Graph context")
701
702    def __contexts(self, triple: _TripleType) -> Generator[_ContextType, None, None]:
703        """return a generator for all the non-quoted contexts
704        (dereferenced) the encoded triple appears in"""
705        # type error: Argument 2 to "get" of "Mapping" has incompatible type "str"; expected "Optional[Graph]"
706        return (
707            self.__context_obj_map.get(ctx_str, ctx_str)  # type: ignore[arg-type]
708            for ctx_str in self.__get_context_for_triple(triple, skipQuoted=True)
709            if ctx_str is not None
710        )
711
712    # type error: Missing return statement
713    def query(  # type: ignore[return]
714        self,
715        query: Union[Query, str],
716        initNs: Mapping[str, Any],  # noqa: N803
717        initBindings: Mapping[str, Identifier],  # noqa: N803
718        queryGraph: str,  # noqa: N803
719        **kwargs,
720    ) -> Result:
721        super(Memory, self).query(query, initNs, initBindings, queryGraph, **kwargs)
722
723    def update(
724        self,
725        update: Union[Update, Any],
726        initNs: Mapping[str, Any],  # noqa: N803
727        initBindings: Mapping[str, Identifier],  # noqa: N803
728        queryGraph: str,  # noqa: N803
729        **kwargs,
730    ) -> None:
731        super(Memory, self).update(update, initNs, initBindings, queryGraph, **kwargs)