
    PiP                      d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z) ddl*Z+ddl,m-Z- dd	l"m.Z. dd
l$m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF erddlGZHddl(Z+ddlImJZJmKZK eDZLeDZMeDZNeAZOed         ZPed         ZQeddded         f         ZRed         ZSeddded         f         ZTeed         ed         ed         f         ZUeed         e7ed         f         ZVeed         ed         ed         ed         f         ZWeed         e7ed         ed         f         ZXed         ZYed         ZZeed         eed                  ed         f         Z[eed         eed                  ed         ed         f         Z\ed         Z]ede7df         Z^ed         Z_eeeeL         eeM         eeN         f         eeeL         eeM         eeN         f         eeeL         eeM         eeN         f         f         Z` edd !          Za ed"d#!          Zb ed$d%!          ZceCsJ e0sJ erdd&ldmeZe  ejf        eg          Zhg d'Zi ed(          Zj G d) d eD          ZkekZl G d* d#ek          Zm eFd+          Zn G d, d%em          Zo G d- d.ek          Zpd/e+jq        jr        ep<    G d0 d1          Zs G d2 d3et          Zu G d4 d5et          Zv G d6 d7em          ZwedCd<            ZxedDd?            ZxdDd@Zx G dA dB          ZydS )Eak$  
RDFLib defines the following kinds of Graphs:

* [`Graph`][rdflib.graph.Graph]
* [`QuotedGraph`][rdflib.graph.QuotedGraph]
* [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]
* [`Dataset`][rdflib.graph.Dataset]

## Graph

An RDF graph is a set of RDF triples. Graphs support the python `in`
operator, as well as iteration and some operations like union,
difference and intersection.

See [`Graph`][rdflib.graph.Graph]

## Conjunctive Graph

!!! warning "Deprecation notice"
    `ConjunctiveGraph` is deprecated, use [`Dataset`][rdflib.graph.Dataset] instead.

A Conjunctive Graph is the most relevant collection of graphs that are
considered to be the boundary for closed world assumptions. This
boundary is equivalent to that of the store instance (which is itself
uniquely identified and distinct from other instances of
[`Store`][rdflib.store.Store] that signify other Conjunctive Graphs). It is
equivalent to all the named graphs within it and associated with a
`_default_` graph which is automatically assigned a
[`BNode`][rdflib.term.BNode] for an identifier - if one isn't given.

See [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]

## Quoted graph

The notion of an RDF graph [14] is extended to include the concept of
a formula node. A formula node may occur wherever any other kind of
node can appear. Associated with a formula node is an RDF graph that
is completely disjoint from all other graphs; i.e. has no nodes in
common with any other graph. (It may contain the same labels as other
RDF graphs; because this is, by definition, a separate graph,
considerations of tidiness do not apply between the graph at a formula
node and any other graph.)

This is intended to map the idea of "{ N3-expression }" that is used
by N3 into an RDF graph upon which RDF semantics is defined.

See [`QuotedGraph`][rdflib.graph.QuotedGraph]

## Dataset

The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The
primary term is "graphs in the datasets" and not "contexts with quads"
so there is a separate method to set/retrieve a graph in a dataset and
to operate with dataset graphs. As a consequence of this approach,
dataset graphs cannot be identified with blank nodes, a name is always
required (RDFLib will automatically add a name if one is not provided
at creation time). This implementation includes a convenience method
to directly add a single quad to a dataset graph.

See [`Dataset`][rdflib.graph.Dataset]

## Working with graphs

Instantiating Graphs with default store (Memory) and default identifier
(a BNode):

```python
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.stores.memory.Memory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>

```

Instantiating Graphs with a Memory store and an identifier -
<https://rdflib.github.io>:

```python
>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g)  # doctest: +NORMALIZE_WHITESPACE
"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
 [a rdflib:Store;rdfs:label 'Memory']."

```

Creating a ConjunctiveGraph - The top level container for all named Graphs
in a "database":

```python
>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']]."

```

Adding / removing reified triples to Graph and iterating over it directly or
via triple pattern:

```python
>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
...     URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
4
>>> for s, p, o in g:
...     print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>

>>> for s, p, o in g.triples((None, RDF.object, None)):
...     print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
3

```

`None` terms in calls to [`triples()`][rdflib.graph.Graph.triples] can be
thought of as "open variables".

Graph support set-theoretic operators, you can add/subtract graphs, as
well as intersection (with multiplication operator g1*g2) and xor (g1
^ g2).

Note that BNode IDs are kept when doing set-theoretic operations, this
may or may not be what you want. Two named graphs within the same
application probably want share BNode IDs, two graphs with data from
different sources probably not. If your BNode IDs are all generated
by RDFLib they are UUIDs and unique.

```python
>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef("http://example.com/foo")
>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(g1 + g2)  # adds bing as label
3
>>> len(g1 - g2)  # removes foo
1
>>> len(g1 * g2)  # only foo
1
>>> g1 += g2  # now g1 contains everything

```

Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within
the same store:

```python
>>> store = plugin.get("Memory", Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.object, Literal(
...     'The top-level aggregate graph - The sum ' +
...     'of all named graphs within a Store'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
...     RDF.type, RDF.Statement)))
2

```

ConjunctiveGraphs have a [`quads()`][rdflib.graph.ConjunctiveGraph.quads] method
which returns quads instead of triples, where the fourth item is the Graph
(or subclass thereof) instance in which the triple was asserted:

```python
>>> uniqueGraphNames = set(
...     [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
...     ).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set(
...     [graph.identifier for s, p, o, graph in unionGraph.quads(
...     (None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2

```

Parsing N3 from a string:

```python
>>> g2 = Graph()
>>> src = '''
... @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
...   rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
...   rdf:predicate rdfs:label;
...   rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format="n3")
>>> print(len(g2))
4

```

Using Namespace class:

```python
>>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
rdflib.term.URIRef('https://rdflib.github.io/Graph')

```
    )annotationsN)BytesIO)IOTYPE_CHECKINGAnyBinaryIOCallableDict	GeneratorIterableListMappingNoReturnOptionalSetTextIOTupleTypeTypeVarUnioncastoverload)urlparse)url2pathname
Collection)ParserError)RDF	NamespaceNamespaceManager)InputSourceParsercreate_input_source)Path)Resource)
Serializer)Store)BNodeGenidIdentifiedNode
IdentifierLiteralNodeRDFLibGenidURIRef)QueryUpdate)_SubjectType_PredicateType_ObjectType)r2   r3   r4   _ContextTyper2   r3   r4   r5   )_TripleType_OptionalQuadType_ContextIdentifierType)_TriplePatternType_QuadPatternType)_TriplePathPatternType_QuadPathPatternType)r$   r3   )_TripleSelectorType_QuadSelectorType)r6   _TriplePathType_GraphTGraph)bound_ConjunctiveGraphTConjunctiveGraph	_DatasetTDataset)_NamespaceSetString) rA   rD   QuotedGraphSeqModificationExceptionrF   UnSupportedAggregateOperationReadOnlyGraphAggregateBatchAddGraphrC   r8   rE   r@   r4   _OptionalIdentifiedQuadTyper7   r3   r<   r:   r>   	_QuadTyper2   _TripleOrOptionalQuadType_TripleOrTriplePathType_TripleOrQuadPathPatternType_TripleOrQuadPatternType_TripleOrQuadSelectorTyper;   r?   r9   r=   r6   _TCArgTc                  |    e Zd ZU dZded<   ded<   ded<   ded<   	 	 	 	 	 dd fdZedd            Zedd            Zedd            Z	e	j
        dd            Z	ddZdd Zdd#Zdd%Zdd&Zdd'Z	 ddd,Zddd.Zdd1Zdd4Zdd6Zedd8            Zedd;            Zedd>            Zdd?Zd@ ZddBZddCZddDZddEZddFZddGZddHZd dJZ ddKZ!d dLZ"ddNZ#ddOZ$ddPZ%ddQZ&ddRZ'ddSZ(e%Z)e&Z*ddUZ+	 	 	 ddd\Z,	 	 	 dddaZ-	 	 	 ddddZ.	 dd	dfZ/	 	 dd
dhZ0	 dddjZ1	 dddnZ2e	 	 	 	 	 dddr            Z3e	 	 	 	 	 ddds            Z3e	 	 	 	 	 dddu            Z3e	 	 	 	 	 dddv            Z3d	e4j3        d	d	dwfddxZ3dd|Z5	 dddZ6	 dddZ7	 dddZ8ddZ9dddZ:	 	 dddZ;ddZ<dddZ=edd            Z>e	 	 	 d dd            Z>e	 	 	 	 d!d"d            Z>e	 	 	 d d#d            Z>e	 	 	 	 d!d$d            Z>	 	 	 	 d%d&dZ>	 	 	 d'd(dZ?	 	 	 	 	 	 d)d*dZ@	 	 	 	 	 d+d,dǄZA	 	 	 	 d-d.d˄ZBdd/d̄ZCd0d΄ZDd dτZEddЄZFd1d҄ZGd2dՄZHd3d؄ZId4dۄZJ	 	 	 	 d5d6dZK	 d7d8dZLd	dd9dZM xZNS (:  rA   a  An RDF Graph: a Python object containing nodes and relations between them as
    RDF 'triples'.

    This is the central RDFLib object class and Graph objects are almost always present
    in all uses of RDFLib.

    Example:
        The basic use is to create a Graph and iterate through or query its content:

        ```python
        >>> from rdflib import Graph, URIRef
        >>> g = Graph()
        >>> g.add((
        ...     URIRef("http://example.com/s1"),   # subject
        ...     URIRef("http://example.com/p1"),   # predicate
        ...     URIRef("http://example.com/o1"),   # object
        ... )) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

        >>> g.add((
        ...     URIRef("http://example.com/s2"),   # subject
        ...     URIRef("http://example.com/p2"),   # predicate
        ...     URIRef("http://example.com/o2"),   # object
        ... )) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

        >>> for triple in sorted(g):  # simple looping
        ...     print(triple)
        (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))
        (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))

        >>> # get the object of the triple with subject s1 and predicate p1
        >>> o = g.value(
        ...     subject=URIRef("http://example.com/s1"),
        ...     predicate=URIRef("http://example.com/p1")
        ... )

        ```


    Args:
        store: The constructor accepts one argument, the "store" that will be used to store the
            graph data with the default being the [`Memory`][rdflib.plugins.stores.memory.Memory]
            (in memory) Store. Other Stores that persist content to disk using various file
            databases or Stores that use remote servers (SPARQL systems) are supported.
            All [builtin storetypes][rdflib.plugins.stores] can be accessed via
            their registered names.
            Other Stores not shipped with RDFLib can be added as plugins, such as
            [HDT](https://github.com/rdflib/rdflib-hdt/).
            Registration of external plugins
            is described in [`rdflib.plugin`][rdflib.plugin].

            Stores can be context-aware or unaware. Unaware stores take up
            (some) less space but cannot support features that require
            context, such as true merging/demerging of sub-graphs and
            provenance.

            Even if used with a context-aware store, Graph will only expose the quads which
            belong to the default graph. To access the rest of the data the
            `Dataset` class can be used instead.

            The Graph constructor can take an identifier which identifies the Graph
            by name. If none is given, the graph is assigned a BNode for its
            identifier.

            For more on Named Graphs, see the RDFLib `Dataset` class and the TriG Specification,
            <https://www.w3.org/TR/trig/>.
        identifier: identifier of the graph itself
        namespace_manager: Used namespace manager.
            Create with bind_namespaces if `None`.
        base: Base used for [URIs][rdflib.term.URIRef]
        bind_namespaces: Used bind_namespaces for namespace_manager
            Is only used, when no namespace_manager is provided.
    boolcontext_awareformula_awaredefault_unionOptional[str]basedefaultNrdflibstoreUnion[Store, str]
identifier,Optional[Union[_ContextIdentifierType, str]]namespace_managerOptional[NamespaceManager]bind_namespacesrG   c                   t          t          |                                            || _        |  |pt	                      | _        t          | j        t                    st          | j                  | _        |  t          |t                    s* t          j        |t                                x| _        }n|| _        || _        || _        d| _        d| _        d| _        d S NF)superrA   __init__r\   r(   _Graph__identifier
isinstancer*   r/   r'   pluginget_Graph__store_Graph__namespace_manager_bind_namespacesrX   rY   rZ   )selfr_   ra   rc   r\   re   	__class__s         `/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/rdflib/graph.pyri   zGraph.__init__  s     	eT##%%%	1&1%''$+^<< 	: &t'8 9 9D%'' 	!#;6:eU#;#;#=#==DL55 DL#4  /"""    returnr'   c                    | j         S N)rn   rq   s    rs   r_   zGraph.store"  s
    |rt   r8   c                    | j         S rw   )rj   rx   s    rs   ra   zGraph.identifier&  s      rt   r    c                R    | j         t          | | j                  | _         | j         S )z0
        this graph's namespace-manager
        )ro   r    rp   rx   s    rs   rc   zGraph.namespace_manager*  s+    
 #+'7d>S'T'TD$''rt   nmNonec                    || _         d S rw   )ro   )rq   r{   s     rs   rc   zGraph.namespace_manager3  s    #%   rt   strc                8    d| j         dt          |           dS )Nz<Graph identifier=z (z)>)ra   typerx   s    rs   __repr__zGraph.__repr__7  s     /3T



KKrt   c                    t          | j        t                    r.| j                                        d| j        j        j        dS d| j        j        j        z  S )Nz9 a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'z'].z?[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']].)rk   ra   r/   n3r_   rr   __name__rx   s    rs   __str__zGraph.__str__:  sf    dov.. 	. ##%%%%tz';'D'D'DF F
 W
$-. .rt   rq   r@   c                    | S rw    rx   s    rs   toPythonzGraph.toPythonD      rt   configurationc                :    | j                             |           | S )z<Destroy the store identified by `configuration` if supported)rn   destroyrq   r   s     rs   r   zGraph.destroyG  s    ]+++rt   c                8    | j                                          | S )zCommits active transactions)rn   commitrx   s    rs   r   zGraph.commitM  s    rt   c                8    | j                                          | S )zRollback active transactions)rn   rollbackrx   s    rs   r   zGraph.rollbackR  s    rt   FUnion[str, tuple[str, str]]createOptional[int]c                8    | j                             ||          S )zOpen the graph store

        Might be necessary for stores that require opening a connection to a
        database or acquiring some resource.
        )rn   open)rq   r   r   s      rs   r   z
Graph.openW  s     |  777rt   commit_pending_transactionc                8    | j                             |          S )zClose the graph store

        Might be necessary for stores that require closing a connection to a
        database or releasing some resource.
        )r   )rn   close)rq   r   s     rs   r   zGraph.closea  s     |!!=W!XXXrt   tripler6   c                $   |\  }}}t          |t                    sJ d|d            t          |t                    sJ d|d            t          |t                    sJ d|d            | j                            |||f| d           | S )zAdd a triple with self as context.

        Args:
            triple: The triple to add to the graph.

        Returns:
            The graph instance.
        Subject  must be an rdflib term
Predicate Object Fquoted)rk   r-   rn   addrq   r   spos        rs   r   z	Graph.addi  s     1a!T""NNN111$NNN"!T""PPPQQQ$PPP"!T""MMM!!!$MMM"!QD777rt   quadsIterable[_QuadType]c                T      j                              fd|D                         S )%Add a sequence of triple with contextc              3     K   | ]C\  }}}}t          |t                    r'|j        j        u *t          |||          ;||||fV  Dd S rw   )rk   rA   ra   _assertnode.0r   r   r   crq   s        rs   	<genexpr>zGraph.addN.<locals>.<genexpr>|  sx       
 
1a!U##
 //Aq!$$ 0 1aL 0///	
 
rt   )rn   addNrq   r   s   ` rs   r   z
Graph.addNy  sL     	 
 
 
 
#
 
 
 	
 	
 	
 rt   r9   c                >    | j                             ||            | S )zRemove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
        context)rn   removerq   r   s     rs   r   zGraph.remove  s$     	FD111rt   "Generator[_TripleType, None, None]c                    d S rw   r   r   s     rs   tripleszGraph.triples  	     .1Srt   r;   &Generator[_TriplePathType, None, None]c                    d S rw   r   r   s     rs   r   zGraph.triples  	     25rt   r=   .Generator[_TripleOrTriplePathType, None, None]c                    d S rw   r   r   s     rs   r   zGraph.triples  	     :=rt   c              #     K   |\  }}}t          |t                    r&|                    | ||          D ]\  }}|||fV  dS | j                            |||f|           D ]\  \  }}}}|||fV  dS )a  Generator over the triple store.

        Returns triples that match the given triple pattern. If the triple pattern
        does not provide a context, all contexts will be searched.

        Args:
            triple: A triple pattern where each component can be a specific value or None
                as a wildcard. The predicate can also be a path expression.

        Yields:
            Triples matching the given pattern.
        r   N)rk   r$   evalrn   r   )	rq   r   r   r   r   _s_o_pcgs	            rs   r   zGraph.triples  s        1aa 	!&&q!,,    B!Ri    %)L$8$8!QD$8$Q$Q ! ! Rb"bj    ! !rt   c                F   t          |t                    r|j        |j        |j        }}}||||                     |||f          S |||                     |          S |||                     |          S |||                     |          S || 	                    ||          S || 
                    ||          S ||                     ||          S |||f| v S t          |t          t          f          r|                     |          S t          d          )ah  
        A graph can be "sliced" as a shortcut for the triples method
        The python slice syntax is (ab)used for specifying triples.
        A generator over matches is returned,
        the returned tuples include only the parts not given

        ```python
        >>> import rdflib
        >>> g = rdflib.Graph()
        >>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

        >>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
        [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]

        >>> list(g[:namespace.RDFS.label]) # all label triples
        [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]

        >>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
        [(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]

        ```

        Combined with SPARQL paths, more complex queries can be
        written concisely:

        - Name of all Bobs friends: `g[bob : FOAF.knows/FOAF.name ]`
        - Some label for Bob: `g[bob : DC.title|FOAF.name|RDFS.label]`
        - All friends and friends of friends of Bob: `g[bob : FOAF.knows * "+"]`
        - etc.

        !!! example "New in version 4.0"
        NzWYou can only index a graph by a single rdflib term or path, or a slice of rdflib terms.)rk   slicestartstopstepr   subject_predicatessubject_objectspredicate_objectssubjects
predicatesobjectsr$   r-   	TypeError)rq   itemr   r   r   s        rs   __getitem__zGraph.__getitem__  sK   F dE"" %	j$)TY!qAyQY19||Q1I...qy..q111qy++A...qy--a000 }}Q*** q!,,, ||Aq))) 1ayD((tTl++ 	))$/// i  rt   intc                8    | j                             |           S )zReturns the number of triples in the graph.

        If context is specified then the number of triples in the context is
        returned instead.

        Returns:
            The number of triples in the graph.
        r   )rn   __len__rx   s    rs   r   zGraph.__len__  s     |##D#111rt   c                ,    |                      d          S )z}Iterates over all triples in the store.

        Returns:
            A generator yielding all triples in the store.
        NNNr   rx   s    rs   __iter__zGraph.__iter__  s     ||.///rt   c                :    |                      |          D ]} dS dS )zSupport for 'triple in graph' syntax.

        Args:
            triple: The triple pattern to check for.

        Returns:
            True if the triple pattern exists in the graph, False otherwise.
        TFr   r   s     rs   __contains__zGraph.__contains__  s+     ll6** 	 	F44urt   c                *    t          | j                  S rw   )hashra   rx   s    rs   __hash__zGraph.__hash__#  s    DO$$$rt   c                z    |dS t          |t                    r!| j        |j        k    | j        |j        k     z
  S dS )N   rk   rA   ra   rq   others     rs   __cmp__zGraph.__cmp__&  sI    =2u%% 	Oe&66%"22  1rt   c                L    t          |t                    o| j        |j        k    S rw   r   r   s     rs   __eq__zGraph.__eq__3  s!    %''ODOu?O,OOrt   c                T    |d u p$t          |t                    o| j        |j        k     S rw   r   r   s     rs   __lt__zGraph.__lt__6  s/     
ue$$K5;K)K	
rt   r   c                    | |k     p| |k    S rw   r   r   s     rs   __le__zGraph.__le__;      e|,tu},rt   c                T    t          |t                    r| j        |j        k    p|d uS rw   r   r   s     rs   __gt__zGraph.__gt__>  s0    5%((OT_u?O-O 
	
rt   c                    | |k    p| |k    S rw   r   r   s     rs   __ge__zGraph.__ge__C  r   rt   Iterable[_TripleType]c                J                            fd|D                         S )zKAdd all triples in Graph other to Graph.
        BNode IDs are not changed.c              3  ,   K   | ]\  }}}|||fV  d S rw   r   )r   r   r   r   rq   s       rs   r   z!Graph.__iadd__.<locals>.<genexpr>I  s1      77gaA1aD/777777rt   r   r   s   ` rs   __iadd__zGraph.__iadd__F  s1     			7777777777rt   c                :    |D ]}|                      |           | S )zRSubtract all triples in Graph other from Graph.
        BNode IDs are not changed.)r   )rq   r   r   s      rs   __isub__zGraph.__isub__L  s-      	  	 FKKrt   c                   	  t          |                       }n# t          $ r t                      }Y nw xY wt          t	          |                                           t	          |                                          z             D ]\  }}|                    ||           | D ]}|                    |           |D ]}|                    |           |S )z6Set-theoretic union
        BNode IDs are not changed.)r   r   rA   setlist
namespacesbindr   )rq   r   retvalprefixurixys          rs   __add__zGraph.__add__S  s    	T$ZZ\\FF 	 	 	WWFFF	tDOO$5$566e>N>N>P>P9Q9QQRR 	% 	%KFCKK$$$$ 	 	AJJqMMMM 	 	AJJqMMMM    55c                    	  t          |                       }n# t          $ r t                      }Y nw xY w|D ]}|| v r|                    |           |S )z>Set-theoretic intersection.
        BNode IDs are not changed.r   r   rA   r   rq   r   r   r  s       rs   __mul__zGraph.__mul__b  so    	T$ZZ\\FF 	 	 	WWFFF	 	 	ADyy

1r  c                    	  t          |                       }n# t          $ r t                      }Y nw xY w| D ]}||vr|                    |           |S )z<Set-theoretic difference.
        BNode IDs are not changed.r  r	  s       rs   __sub__zGraph.__sub__n  so    	T$ZZ\\FF 	 	 	WWFFF	 	 	A~~

1r  c                    | |z
  || z
  z   S )z5Set-theoretic XOR.
        BNode IDs are not changed.r   r   s     rs   __xor__zGraph.__xor__z  s     u..rt   0Tuple[_SubjectType, _PredicateType, _ObjectType]c                    |\  }}}|
J d            |
J d            |                      ||df           |                     |||f           | S )zConvenience method to update the value of object

        Remove any existing triples for subject and predicate before adding
        (subject, predicate, object).
        Nz>s can't be None in .set([s,p,o]), as it would remove (*, p, *)z>p can't be None in .set([s,p,o]), as it would remove (s, *, *))r   r   )rq   r   subject	predicateobject_s        rs   r   z	Graph.set  sw     )/%)WK   !!K "!!Wi.///'9g.///rt   r  !Union[None, Path, _PredicateType]object/Optional[Union[_ObjectType, List[_ObjectType]]]unique#Generator[_SubjectType, None, None]c              #    K   t          |t                    r%|D ] }|                     |||          D ]}|V  !dS |s%|                     d||f          D ]
\  }}}|V  dS t	                      }|                     d||f          D ]U\  }}}||vrK|V  	 |                    |           %# t          $ r#}	t                              |	 d            d}	~	ww xY wVdS )a_  A generator of (optionally unique) subjects with the given
        predicate and object(s)

        Args:
            predicate: A specific predicate to match or None to match any predicate.
            object: A specific object or list of objects to match or None to match any object.
            unique: If True, only yield unique subjects.
        N1. Consider not setting parameter 'unique' to True)	rk   r   r   r   r   r   MemoryErrorloggererror)
rq   r  r  r  objr   r   r   subses
             rs   r   zGraph.subjects  sY      fd## 	"  y#v>>  AGGGG   "#||T9f,EFF  GAq!GGGG  uu#||T9f,EFF 	" 	"GAq!}}" HHQKKKK* " " ""LL#$ W W W   "	"	 %	" 	"   B//
C9CCr  Optional[_SubjectType]Optional[_ObjectType]%Generator[_PredicateType, None, None]c              #  P  K   |s%|                      |d|f          D ]
\  }}}|V  dS t                      }|                      |d|f          D ]U\  }}}||vrK|V  	 |                    |           %# t          $ r#}t                              | d            d}~ww xY wVdS )as  Generate predicates with the given subject and object.

        Args:
            subject: A specific subject to match or None to match any subject.
            object: A specific object to match or None to match any object.
            unique: If True, only yield unique predicates.

        Yields:
            Predicates matching the given subject and object.
        Nr  r   r   r   r  r  r  )	rq   r  r  r  r   r   r   predsr   s	            rs   r   zGraph.predicates  s         	<<$(?@@  1a  EEE<<$(?@@ 	 	1aE>>GGG		!&    SSS   		 "	 	s   A55
B"?BB"1Optional[Union[_SubjectType, List[_SubjectType]]]"Generator[_ObjectType, None, None]c              #    K   t          |t                    r%|D ] }|                     |||          D ]}|V  !dS |s%|                     ||df          D ]
\  }}}|V  dS t	                      }|                     ||df          D ]U\  }}}||vrK|V  	 |                    |           %# t          $ r#}	t                              |	 d            d}	~	ww xY wVdS )a  A generator of (optionally unique) objects with the given
        subject(s) and predicate

        Args:
            subject: A specific subject or a list of subjects to match or None to match any subject.
            predicate: A specific predicate to match or None to match any predicate.
            unique: If True, only yield unique objects.

        Yields:
            Objects matching the given subject and predicate.
        Nr  )	rk   r   r   r   r   r   r  r  r  )
rq   r  r  r  subjr   r   r   objsr   s
             rs   r   zGraph.objects  sY     " gt$$ 	"  dIv>>  AGGGG   "#||Wi,FGG  GAq!GGGG  uu#||Wi,FGG 	" 	"GAq!}}" HHQKKKK* " " ""LL#$ W W W   "	"	 %	" 	"r!  :Generator[Tuple[_SubjectType, _PredicateType], None, None]c              #  `  K   |s'|                      dd|f          D ]\  }}}||fV  dS t                      }|                      dd|f          D ][\  }}}||f|vrO||fV  	 |                    ||f           +# t          $ r#}t                              | d            d}~ww xY w\dS )z[A generator of (optionally unique) (subject, predicate) tuples
        for the given objectNr  r&  )rq   r  r  r   r   r   
subj_predsr   s           rs   r   zGraph.subject_predicates  s     
  	<<tV(<==  1ad



  J<<tV(<== 	 	1aq6++Q$JJJ"1v....&    SSS   		 ,	 	   %A==
B*B%%B*7Generator[Tuple[_SubjectType, _ObjectType], None, None]c              #  `  K   |s'|                      d|df          D ]\  }}}||fV  dS t                      }|                      d|df          D ][\  }}}||f|vrO||fV  	 |                    ||f           +# t          $ r#}t                              | d            d}~ww xY w\dS )z[A generator of (optionally unique) (subject, object) tuples
        for the given predicateNr  r&  )rq   r  r  r   r   r   	subj_objsr   s           rs   r   zGraph.subject_objects  s       	<<y$(?@@  1ad



  I<<y$(?@@ 	 	1aq6**Q$JJJ!q!f----&    SSS   		 +	 	r0  9Generator[Tuple[_PredicateType, _ObjectType], None, None]c              #  `  K   |s'|                      |ddf          D ]\  }}}||fV  dS t                      }|                      |ddf          D ][\  }}}||f|vrO||fV  	 |                    ||f           +# t          $ r#}t                              | d            d}~ww xY w\dS )z[A generator of (optionally unique) (predicate, object) tuples
        for the given subjectNr  r&  )rq   r  r  r   r   r   	pred_objsr   s           rs   r   zGraph.predicate_objects-  s     
  	<<$(=>>  1ad



  I<<$(=>> 	 	1aq6**Q$JJJ!q!f----&    SSS   		 +	 	r0  _TripleChoiceTyper   Optional[_ContextType]c              #  v   K   |\  }}}| j                             |||f|           D ]\  \  }}}}	|||fV  d S )Nr   )r_   triples_choices)
rq   r   r   r  r  r  r   r   r   r   s
             rs   r:  zGraph.triples_choicesB  so      
 '-#G "Z77i)4 8 
 
 	 	MIQ1r Q'MMMM	 	rt   .Optional[Node]anyc                    d S rw   r   rq   r  r  r  r]   r<  s         rs   valuezGraph.valueO  	     srt   c                    d S rw   r   r>  s         rs   r?  zGraph.valueY  r@  rt   Optional[_PredicateType]c                    d S rw   r   r>  s         rs   r?  zGraph.valuec  r@  rt   c                    d S rw   r   r>  s         rs   r?  zGraph.valuem  s	     rt   Tc                   |}||||||dS ||                      ||          }||                     ||          }||                     ||          }	 t          |          }|du r	 t          |           d|d|d|d}| j                            |||fd          }	|	D ](\  \  }
}}}|d|
d|d|dt          |          d	z  })t          j        |          # t          $ r Y nw xY wn# t          $ r |}Y nw xY w|S )	a	  Get a value for a pair of two criteria

        Exactly one of subject, predicate, object must be None. Useful if one
        knows that there may only be one value.

        It is one of those situations that occur a lot, hence this
        'macro' like utility

        Args:
            subject: Subject of the triple pattern, exactly one of subject, predicate, object must be None
            predicate: Predicate of the triple pattern, exactly one of subject, predicate, object must be None
            object: Object of the triple pattern, exactly one of subject, predicate, object must be None
            default: Value to be returned if no values found
            any: If True, return any value in the case there is more than one, else, raise UniquenessError
        NFz"While trying to find a value for (z, z-) the following multiple values where found:
(z)
 (contexts: z)
)
r   r   r   nextr_   r   r   
exceptionsUniquenessErrorStopIteration)rq   r  r  r  r]   r<  r   valuesmsgr   r   r   r   contextss                 rs   r?  zGraph.valuew  s   .  _!2FN!fn4>\\'955F?]]9f55F__Wf55F	&\\F e||LLLL #77IIIvvv7 
 #j00'9f1MtTTG/6  +	Aq8AAAAAA NNNN	   %4S999$   D#   	 	 	FFF	, s%   C7 .A8C& &
C32C37DDr   r-   Generator[Node, None, None]c              #    K   t          |g          }|rr|                     |t          j                  }||V  |                     |t          j                  }||v rt          d          |                    |           |pdS dS )zwGenerator over all items in the resource specified by list

        Args:
            list: An RDF collection.
        Nz,List contains a recursive rdf:rest reference)r   r?  r   firstrest
ValueErrorr   )rq   r   chainr   s       rs   itemszGraph.items  s       TF 	::dCI..D


::dCH--Du}} !OPPPIIdOOO  	 	 	 	 	rt   func-Callable[[_TCArgT, Graph], Iterable[_TCArgT]]argrU   seenOptional[Dict[_TCArgT, int]]c              #     K   |i }n||v rdS d||<    |||           D ]$}|V  |                      |||          D ]}|V  %dS )a  Generates transitive closure of a user-defined function against the graph

        ```python
        from rdflib.collection import Collection
        g = Graph()
        a = BNode("foo")
        b = BNode("bar")
        c = BNode("baz")
        g.add((a,RDF.first,RDF.type))
        g.add((a,RDF.rest,b))
        g.add((b,RDF.first,namespace.RDFS.label))
        g.add((b,RDF.rest,c))
        g.add((c,RDF.first,namespace.RDFS.comment))
        g.add((c,RDF.rest,RDF.nil))
        def topList(node,g):
           for s in g.subjects(RDF.rest, node):
              yield s
        def reverseList(node,g):
           for f in g.objects(node, RDF.first):
              print(f)
           for s in g.subjects(RDF.rest, node):
              yield s

        [rt for rt in g.transitiveClosure(
            topList,RDF.nil)]
        # [rdflib.term.BNode('baz'),
        #  rdflib.term.BNode('bar'),
        #  rdflib.term.BNode('foo')]

        [rt for rt in g.transitiveClosure(
            reverseList,RDF.nil)]
        # http://www.w3.org/2000/01/rdf-schema#comment
        # http://www.w3.org/2000/01/rdf-schema#label
        # http://www.w3.org/1999/02/22-rdf-syntax-ns#type
        # [rdflib.term.BNode('baz'),
        #  rdflib.term.BNode('bar'),
        #  rdflib.term.BNode('foo')]
        ```

        Args:
            func: A function that generates a sequence of nodes
            arg: The starting node
            seen: A dict of visited nodes
        Nr   )transitiveClosure)rq   rU  rW  rX  rtrt_2s         rs   r[  zGraph.transitiveClosure  s      d <DDD[[FS	$sD// 	 	BHHH..tR>>  



	 	rt   remember+Optional[Dict[Optional[_SubjectType], int]]-Generator[Optional[_SubjectType], None, None]c              #     K   |i }||v rdS d||<   |V  |                      ||          D ] }|                     |||          D ]}|V  !dS )a  Transitively generate objects for the ``predicate`` relationship

        Generated objects belong to the depth first transitive closure of the
        `predicate` relationship starting at `subject`.

        Args:
            subject: The subject to start the transitive closure from
            predicate: The predicate to follow
            remember: A dict of visited nodes
        Nr   )r   transitive_objects)rq   r  r  r^  r  r   s         rs   rb  zGraph.transitive_objects  s        HhFll7I66 	 	F,,VYII  	 	rt   *Optional[Dict[Optional[_ObjectType], int]],Generator[Optional[_ObjectType], None, None]c              #     K   |i }||v rdS d||<   |V  |                      ||          D ] }|                     |||          D ]}|V  !dS )a  Transitively generate subjects for the ``predicate`` relationship

        Generated subjects belong to the depth first transitive closure of the
        `predicate` relationship starting at `object`.

        Args:
            predicate: The predicate to follow
            object: The object to start the transitive closure from
            remember: A dict of visited nodes
        Nr   )r   transitive_subjects)rq   r  r  r^  r  r   s         rs   rf  zGraph.transitive_subjects  s        HXF}}Y77 	 	G--i(KK  	 	rt   r  c                6    | j                             |          S rw   )rc   qnamerq   r  s     rs   rh  zGraph.qname9  s    %++C000rt   generateTuple[str, URIRef, str]c                8    | j                             ||          S rw   )rc   compute_qnamerq   r  rj  s      rs   rm  zGraph.compute_qname<  s    %33CBBBrt   r  	namespacer   overridereplacec                >    | j                             ||||          S )a\  Bind prefix to namespace

        If override is True will bind namespace to given prefix even
        if namespace was already bound to a different prefix.

        if replace, replace any existing prefix with the new namespace

        Args:
            prefix: The prefix to bind
            namespace: The namespace to bind the prefix to
            override: If True, override any existing prefix binding
            replace: If True, replace any existing namespace binding

        Example:
            ```python
            graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
            ```
        )rp  rq  )rc   r   )rq   r  ro  rp  rq  s        rs   r   z
Graph.bind?  s.    @ %**I' + 
 
 	
rt   )Generator[Tuple[str, URIRef], None, None]c              #  T   K   | j                                         D ]\  }}||fV  dS )zGenerator over all the prefix, namespace tuples

        Returns:
            Generator yielding prefix, namespace tuples
        N)rc   r   )rq   r  ro  s      rs   r   zGraph.namespacesc  sI       "&!7!B!B!D!D 	$ 	$FI)#####	$ 	$rt   r   defragr/   c                8    | j                             ||          S )z5Turn uri into an absolute URI if it's not one already)rc   
absolutizerq   r  ru  s      rs   rw  zGraph.absolutizel  s    %00f===rt   destinationformatencodingargsbytesc                    d S rw   r   rq   ry  rz  r\   r{  r|  s         rs   	serializezGraph.serializeq  	     rt   c                   d S rw   r   r  s         rs   r  zGraph.serialize|  	     rt   c                    d S rw   r   r  s         rs   r  zGraph.serialize  	     crt   'Union[str, pathlib.PurePath, IO[bytes]]c                    d S rw   r   r  s         rs   r  zGraph.serialize  r  rt   1Optional[Union[str, pathlib.PurePath, IO[bytes]]]Union[bytes, str, Graph]c                    d S rw   r   r  s         rs   r  zGraph.serialize  	     $'3rt   turtleUnion[bytes, str, _GraphT]c                >   || j         } t          j        |t                    |           }|mt	                      }|8 |j        |f|dd| |                                                    d          S  |j        |f||d| |                                S t          |d          r2t          t          t                   |          } |j        |f||d| nt          |t          j                  rt          |          }n\t          t          |          }	t!          |	          \  }
}}}}}|
dk    r)|dk    rt#          d|	d          t%          |          }n|	}t'          |d	          5 } |j        |f||d| ddd           n# 1 swxY w Y   | S )
a  Serialize the graph.

        Args:
            destination: The destination to serialize the graph to. This can be a path as a
                string or pathlib.PurePath object, or it can be an IO[bytes] like object.
                If this parameter is not supplied the serialized graph will be returned.
            format: The format that the output should be written in. This value
                references a Serializer plugin.
                Format support is managed with [plugins][rdflib.plugin].
                Defaults to "turtle" and some other formats are builtin,
                like "xml" and "trix".
                See also [serialize module][rdflib.plugins.parsers].
            base: The base IRI for formats that support it. For the turtle format this
                will be used as the @base directive.
            encoding: Encoding of output.
            args: Additional arguments to pass to the Serializer that will be used.

        Returns:
            The serialized graph if `destination` is None. The serialized graph is returned
            as str if no encoding is specified, and as bytes if an encoding is specified.

            self (i.e. the Graph instance) if `destination` is not None.
        Nutf-8)r\   r{  writefile zthe file URI z2 has an authority component which is not supportedwb)r\   rl   rm   r&   r   r  getvaluedecodehasattrr   r   r}  rk   pathlibPurePathr~   r   rR  r   r   )rq   ry  rz  r\   r{  r|  
serializerstreamos_pathlocationschemenetlocpathparams_queryfragments                   rs   r  zGraph.serialize  s.   B <9D3VZ
33D99
YYF$
$VQ$QQDQQQ((//888$
$VR$RRTRRR(((;(( 	S"U)[11F J NdXNNNNNN+w'788 'k**[11AI(ASAS>ffhV##||(jHjjj   +400GG&Ggt$$ S$
$VR$RRTRRRS S S S S S S S S S S S S S Ss   4FFFr  outOptional[TextIO]c                |    t          |                     d ||                              |          |d           d S )N)rz  r{  T)r  flush)printr  r  )rq   rz  r{  r  s       rs   r  zGraph.print  sN     	NN4NBBII(SS	
 	
 	
 	
 	
 	
rt   sourceMOptional[Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]]publicIDr  r  !Optional[Union[BinaryIO, TextIO]]dataOptional[Union[str, bytes]]c                b   t          ||||||          }||j        }d}|tt          |d          r^t          |j        dd          rHt          |j        j        t                    r)t          j	        
                    |j        j                  }|d}d}	  t          j        |t                                }	n}# t          j        $ rk t          j	        
                    t          |t                    s|nt          |                    }|  t          j        |t                                }	Y nw xY w	  |	j        || fi | n(# t"          $ r}
|rt%          d|z            |
d}
~
ww xY w	 |j        r|                                 n!# |j        r|                                 w w xY w| S )	a9  Parse an RDF source adding the resulting triples to the Graph.

        The source is specified using one of source, location, file or data.

        Args:
            source: An `xml.sax.xmlreader.InputSource`, file-like object,
                `pathlib.Path` like object, or string. In the case of a string the string
                is the location of the source.
            publicID: The logical URI to use as the document base. If None
                specified the document location is used (at least in the case where
                there is a document location). This is used as the base URI when
                resolving relative URIs in the source document, as defined in `IETF
                RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-5.1.4>`_,
                given the source document does not define a base URI.
            format: Used if format can not be determined from source, e.g.
                file extension or Media Type. Format support is managed
                with [plugins][rdflib.plugin].
                Available formats are e.g. "turle", "xml", "n3", "nt" and "trix"
                or see [parser module][rdflib.plugins.parsers].
            location: A string indicating the relative or absolute URL of the
                source. `Graph`'s absolutize method is used if a relative location
                is specified.
            file: A file-like object.
            data: A string containing the data to be parsed.
            args: Additional arguments to pass to the parser.

        Returns:
            self, i.e. the Graph instance.

        Example:
            ```python
            >>> my_data = '''
            ... <rdf:RDF
            ...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            ...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
            ... >
            ...   <rdf:Description>
            ...     <rdfs:label>Example</rdfs:label>
            ...     <rdfs:comment>This is really just an example.</rdfs:comment>
            ...   </rdf:Description>
            ... </rdf:RDF>
            ... '''
            >>> import os, tempfile
            >>> fd, file_name = tempfile.mkstemp()
            >>> f = os.fdopen(fd, "w")
            >>> dummy = f.write(my_data)  # Returns num bytes written
            >>> f.close()

            >>> g = Graph()
            >>> result = g.parse(data=my_data, format="application/rdf+xml")
            >>> len(g)
            2

            >>> g = Graph()
            >>> result = g.parse(location=file_name, format="application/rdf+xml")
            >>> len(g)
            2

            >>> g = Graph()
            >>> with open(file_name, "r") as f:
            ...     result = g.parse(f, format="application/rdf+xml")
            >>> len(g)
            2

            >>> os.remove(file_name)

            >>> # default turtle parsing
            >>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
            >>> len(g)
            3

            ```

        !!! warning "Caution"
            This method can access directly or indirectly requested network or
            file resources, for example, when parsing JSON-LD documents with
            `@context` directives that point to a network location.

            When processing untrusted or potentially malicious documents,
            measures should be taken to restrict network and file access.

            For information on available security measures, see the RDFLib
            [Security Considerations](../security_considerations.md)
            documentation.
        r  r  r  r  r  rz  NFr  namer  TzCould not guess RDF format for %r from file extension so tried Turtle but failed.You can explicitly specify format using the format argument.)r#   content_typer  getattrr  rk   r  r~   r^   utilguess_formatrl   rm   r"   PluginExceptionr!   parseSyntaxErrorr   
auto_closer   )rq   r  r  rz  r  r  r  r|  could_not_guess_formatparserses              rs   r  zGraph.parse  s   D %
 
 
 >(F!&>''DFK66D v{/55D
  11&+2BCC~!)-&	2/VZ//11FF% 		2 		2 		2 [--(==N3v;; F ~/VZ//11FFF		2	FL...... 	 	 	% !S   	 /      s=   "B; ;A7D54D59E	 F 	
E.E))E..F F,sparqlquery_objectUnion[str, Query]	processorUnion[str, query.Processor]resultUnion[str, Type[query.Result]]initNsOptional[Mapping[str, Any]]initBindings"Optional[Mapping[str, Identifier]]use_store_providedkwargsquery.Resultc                   |pi }|p t          |                                           }| j        rd}n)t          | t                    r| j        j        }n| j        }t          | j        d          r)|r'	  | j        j	        ||||fi |S # t          $ r Y nw xY wt          |t          j                  s2t          j        t          t          |          t          j                  }t          |t          j                  s( t          j        |t          j                  |           } | |j	        |||fi |          S )ai  
        Query this graph.

        Args:
            query_object: The query string or object to execute.
            processor: The query processor to use. Default is "sparql".
            result: The result format to use. Default is "sparql".
            initNs: Initial namespaces to use for resolving prefixes in the query.
                If none are given, the namespaces from the graph's namespace manager are used.
            initBindings: Initial variable bindings to use. A type of 'prepared queries'
                can be realized by providing these bindings.
            use_store_provided: Whether to use the store's query method if available.
            kwargs: Additional arguments to pass to the query processor.

        Returns:
            A [`rdflib.query.Result`][`rdflib.query.Result`] instance.

        !!! warning "Caution"
            This method can access indirectly requested network endpoints, for
            example, query processing will attempt to access network endpoints
            specified in `SERVICE` directives.

            When processing untrusted or potentially malicious queries, measures
            should be taken to restrict network and file access.

            For information on available security measures, see the RDFLib
            [Security Considerations](../security_considerations.md)
            documentation.
        	__UNION__query)dictr   rZ   rk   rD   default_contextra   r  r_   r  NotImplementedErrorResultrl   rm   r   r~   	Processor)	rq   r  r  r  r  r  r  r  query_graphs	            rs   r  zGraph.query  sk   P $)r24 1 122 	*%KK.// 	*.9KK/K4:w'' 
	,> 
		'tz'  	 
    '    &%,// 	AZS& 1 15<@@F)U_55 	E>
9eo>>tDDI voiolL&SSFSSTTT   3B	 	
BBupdate_objectUnion[Update, str](Union[str, rdflib.query.UpdateProcessor]c                   |pi }|p t          |                                           }| j        rd}n)t          | t                    r| j        j        }n| j        }t          | j        d          r)|r'	  | j        j	        ||||fi |S # t          $ r Y nw xY wt          |t          j                  s( t          j        |t          j                  |           } |j	        |||fi |S )ae  Update this graph with the given update query.

        Args:
            update_object: The update query string or object to execute.
            processor: The update processor to use. Default is "sparql".
            initNs: Initial namespaces to use for resolving prefixes in the query.
                If none are given, the namespaces from the graph's namespace manager are used.
            initBindings: Initial variable bindings to use.
            use_store_provided: Whether to use the store's update method if available.
            kwargs: Additional arguments to pass to the update processor.

        !!! warning "Caution"
            This method can access indirectly requested network endpoints, for
            example, query processing will attempt to access network endpoints
            specified in `SERVICE` directives.

            When processing untrusted or potentially malicious queries, measures
            should be taken to restrict network and file access.

            For information on available security measures, see the RDFLib
            Security Considerations documentation.
        r  update)r  r   rZ   rk   rD   r  ra   r  r_   r  r  r  UpdateProcessorrl   rm   )rq   r  r  r  r  r  r  r  s           rs   r  zGraph.update  s/   > $)r24 1 122 	*%KK.// 	*.9KK/K4:x(( 
	-? 
		(tz(! 	 
    '    )U%:;; 	KD
9e.CDDTJJIy|VNNvNNNr  c                >    d| j                             |          z  S )%Return an n3 identifier for the Graphz[%s]rc   ra   r   rq   rc   s     rs   r   zGraph.n3
  !    **=N*OOOOrt   8Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]c                ,    t           | j        | j        ffS rw   )rA   r_   ra   rx   s    rs   
__reduce__zGraph.__reduce__  s    

 	
rt   c                >   t          |           t          |          k    rdS | D ]:\  }}}t          |t                    st          |t                    s
|||f|vr dS ;|D ]:\  }}}t          |t                    st          |t                    s
|||f| vr dS ;dS )a  Check if this graph is isomorphic to another graph.

        Performs a basic check if these graphs are the same.
        If no BNodes are involved, this is accurate.

        Args:
            other: The graph to compare with.

        Returns:
            True if the graphs are isomorphic, False otherwise.

        Note:
            This is only an approximation. See rdflib.compare for a correct
            implementation of isomorphism checks.
        FT)lenrk   r(   )rq   r   r   r   r   s        rs   
isomorphiczGraph.isomorphic  s    " t99E

""5 	! 	!GAq!a'' !
1e0D0D !1ayE)) 55 	! 	!GAq!a'' !
1e0D0D !1ayD(( 55trt   c                "   t          |                                           }g }|sdS |t          j        t	          |                             g}|r|                                }||vr|                    |           |                     |          D ]}||vr||vr|                    |            |                     |          D ]}||vr||vr|                    |            |t	          |          t	          |          k    rdS dS )a  Check if the Graph is connected.

        The Graph is considered undirectional.

        Returns:
            True if all nodes have been visited and there are no unvisited nodes left,
            False otherwise.

        Note:
            Performs a search on the Graph, starting from a random node. Then
            iteratively goes depth-first through the triplets where the node is
            subject and object.
        F)r  )r  T)	r   	all_nodesrandom	randranger  popappendr   r   )rq   r  
discoveredvisitingr  new_xs         rs   	connectedzGraph.connected5  s8    ))**	
  	5f.s9~~>>?@ 		+A
""!!!$$$a00 + +
**uH/D/DOOE***a00 + +
**uH/D/DOOE***  		+ y>>S__,,45rt   	Set[Node]c                    t          |                                           }|                    |                                            |S rw   )r   r   r  r   )rq   ress     rs   r  zGraph.all_nodes^  s6    $,,..!!

4==??###
rt   r2   r   c                "    t          | |          S )aA  Create a new `Collection` instance.

        Args:
            identifier: A URIRef or BNode instance.

        Returns:
            A new Collection instance.

        Example:
            ```python
            >>> graph = Graph()
            >>> uri = URIRef("http://example.org/resource")
            >>> collection = graph.collection(uri)
            >>> assert isinstance(collection, Collection)
            >>> assert collection.uri is uri
            >>> assert collection.graph is graph
            >>> collection += [ Literal(1), Literal(2) ]

            ```
        r   rq   ra   s     rs   
collectionzGraph.collectionc  s    , $
+++rt   Union[Node, str]r%   c                j    t          |t                    st          |          }t          | |          S )a  Create a new ``Resource`` instance.

        Args:
            identifier: A URIRef or BNode instance.

        Returns:
            A new Resource instance.

        Example:
            ```python
            >>> graph = Graph()
            >>> uri = URIRef("http://example.org/resource")
            >>> resource = graph.resource(uri)
            >>> assert isinstance(resource, Resource)
            >>> assert resource.identifier is uri
            >>> assert resource.graph is graph

            ```
        )rk   r-   r/   r%   r  s     rs   resourcezGraph.resource{  s3    ( *d++ 	,
++Jj)))rt   target$Callable[[_TripleType], _TripleType]c                r    |                      d          D ] }|                     ||                     !d S )Nr   )r   r   )rq   r  rU  ts       rs   _process_skolem_tupleszGraph._process_skolem_tuples  sG     011 	  	 AJJttAww	  	 rt   	new_graphOptional[Graph]bnodeOptional[BNode]	authoritybasepathc                    d	fdd
fd}|t                      n|}|                     ||           n/t          t                    r|                     |fd           |S )Nr   r(   r  r6   ru   c                   |\  }}}|| k    r5t           rt          |t                    sJ |                              }|| k    r5t           rt          |t                    sJ |                              }|||fS N)r  r  )r   rk   r(   	skolemize)r   r  r   r   r   r  r  s        rs   do_skolemizez%Graph.skolemize.<locals>.do_skolemize  s    IQ1Ezz  0%a/////KK)hKGGEzz  0%a/////KK)hKGGa7Nrt   c                    | \  }}}t          |t                    r|                              }t          |t                    r|                              }|||fS r  )rk   r(   r  )r  r   r   r   r  r  s       rs   do_skolemize2z&Graph.skolemize.<locals>.do_skolemize2  si    IQ1!U## HKK)hKGG!U## HKK)hKGGa7Nrt   c                     |           S rw   r   )r  r   r  s    rs   <lambda>z!Graph.skolemize.<locals>.<lambda>  s    ,,ua:P:P rt   )r   r(   r  r6   ru   r6   r  r6   ru   r6   )rA   r  rk   r(   )rq   r  r   r  r  r
  r   r  s     ```  @rs   r  zGraph.skolemize  s    
	 
	 
	 
	 
	 
	 
		 	 	 	 	 	 	 &-9=''>>>>u%% 	R''0P0P0P0P0PQQQrt   urirefOptional[URIRef]c                    d	dd
d}|t                      n|}|                     ||           n/t          t                    r|                     |fd           |S )Nr  r/   r  r6   ru   c                    |\  }}}|| k    r2t           rt          |t                    sJ |                                }|| k    r2t           rt          |t                    sJ |                                }|||fS rw   )r   rk   r/   de_skolemize)r  r  r   r   r   s        rs   do_de_skolemizez+Graph.de_skolemize.<locals>.do_de_skolemize  s    IQ1F{{  1%a00000NN$$F{{  1%a00000NN$$a7Nrt   c                   | \  }}}t          j        |          r"t          |                                          }n5t          j        |          r!t          |                                          }t          |t                    rkt          j        |          r"t          |                                          }n5t          j        |          r!t          |                                          }|||fS rw   )r.   _is_rdflib_skolemr  r)   _is_external_skolemrk   r/   )r  r   r   r   s       rs   do_de_skolemize2z,Graph.de_skolemize.<locals>.do_de_skolemize2  s    IQ1,Q// ,NN//11*1-- ,!HH))++!V$$ 0033 0#A3355AA.q11 0a--//Aa7Nrt   c                     |           S rw   r   )r  r  r  s    rs   r  z$Graph.de_skolemize.<locals>.<lambda>  s    //&RS:T:T rt   )r  r/   r  r6   ru   r6   r  )rA   r  rk   r)   )rq   r  r  r  r   r  s     `  @rs   r  zGraph.de_skolemize  s    
	 
	 
	 
		 	 	 	$ &-9>''0@AAAA&& 	V''0T0T0T0T0TUUUrt   )target_graphr  r  c               X     |t                      n|d fd |           S )a  Retrieves the Concise Bounded Description of a Resource from a Graph.

        Args:
            resource: A URIRef object, the Resource to query for.
            target_graph: Optionally, a graph to add the CBD to; otherwise,
                a new graph is created for the CBD.

        Returns:
            A Graph, subgraph of self if no graph was provided otherwise the provided graph.

        Note:
            Concise Bounded Description (CBD) is defined as:

            Given a particular node (the starting node) in a particular RDF graph (the source graph),
            a subgraph of that particular graph, taken to comprise a concise bounded description of
            the resource denoted by the starting node, can be identified as follows:

            1. Include in the subgraph all statements in the source graph where the subject of the
                statement is the starting node;

            2. Recursively, for all statements identified in the subgraph thus far having a blank
                node object, include in the subgraph all statements in the source graph where the
                subject of the statement is the blank node in question and which are not already
                included in the subgraph.

            3. Recursively, for all statements included in the subgraph thus far, for all
                reifications of each statement in the source graph, include the concise bounded
                description beginning from the rdf:Statement node of each reification.

            This results in a subgraph where the object nodes are either URI references, literals,
            or blank nodes not serving as the subject of any statement in the graph.

            See: <https://www.w3.org/Submission/CBD/>
        Nr  r2   ru   r|   c                                        | d d f          D ]F\  }}}	                    |||f           t          |          t          u r|d d f	vr |           G                     d t          j        | f          D ]=\  }}}                     |d d f          D ]\  }}}	                    |||f           >d S rw   )r   r   r   r(   r   r  )
r  r   r   r   s2p2o2
add_to_cbdrq   subgraphs
          rs   r  zGraph.cbd.<locals>.add_to_cbd  s    <<dD(9:: " "1aaAY'''77e##D$x(G(GJqMMM  <<s{C(@AA / /1a"&,,4"?"? / /JBBLL"b"....// /rt   )r  r2   ru   r|   )rA   )rq   r  r  r  r   s   `  @@rs   cbdz	Graph.cbd  s]    J wwHH#H	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/$ 	
8rt   )r]   NNNr^   )
r_   r`   ra   rb   rc   rd   r\   r[   re   rG   )ru   r'   )ru   r8   )ru   r    )r{   r    ru   r|   ru   r~   )rq   r@   ru   r@   )rq   r@   r   r~   ru   r@   F)r   r   r   rW   ru   r   )r   rW   ru   r|   rq   r@   r   r6   ru   r@   rq   r@   r   r   ru   r@   )rq   r@   r   r9   ru   r@   r   r9   ru   r   r   r;   ru   r   r   r=   ru   r   ru   r   )ru   r   )r   r=   ru   rW   )ru   rW   )r   rA   ru   rW   )rq   r@   r   r   ru   r@   )r   rA   ru   rA   )rq   r@   r   r  ru   r@   )NNF)r  r  r  r  r  rW   ru   r  )r  r"  r  r#  r  rW   ru   r$  )r  r(  r  r  r  rW   ru   r)  rg   )r  r#  r  rW   ru   r-  )r  r  r  rW   ru   r1  )r  r"  r  rW   ru   r4  rw   r   r7  r   r8  ru   r   ).....)r  r|   r  r|   r  r#  r]   r;  r<  rW   ru   r|   )r  r"  r  r|   r  r|   r]   r;  r<  rW   ru   r|   )r  r|   r  rB  r  r|   r]   r;  r<  rW   ru   r|   )r  r"  r  rB  r  r#  r]   r;  r<  rW   ru   r;  )r   r-   ru   rN  )rU  rV  rW  rU   rX  rY  )r  r"  r  rB  r^  r_  ru   r`  )r  rB  r  r#  r^  rc  ru   rd  r  r~   ru   r~   Tr  r~   rj  rW   ru   rk  )TF)
r  r[   ro  r   rp  rW   rq  rW   ru   r|   ru   rs  r   )r  r~   ru  r   ru   r/   ry  r|   rz  r~   r\   r[   r{  r~   r|  r   ru   r}  .......ry  r|   rz  r~   r\   r[   r{  r|   r|  r   ru   r~   ry  r  rz  r~   r\   r[   r{  r[   r|  r   ru   rA   ry  r  rz  r~   r\   r[   r{  r[   r|  r   ru   r  )Nr  NN)rq   r@   ry  r  rz  r~   r\   r[   r{  r[   r|  r   ru   r  )r  r  N)rz  r~   r{  r~   r  r  ru   r|   NNNNNNr  r  r  r[   rz  r[   r  r[   r  r  r  r  r|  r   ru   rA   )r  r  NNT)r  r  r  r  r  r  r  r  r  r  r  rW   r  r   ru   r  )r  NNT)r  r  r  r  r  r  r  r  r  rW   r  r   ru   r|   rc   rd   ru   r~   ru   r  )ru   r  )ra   r2   ru   r   )ra   r  ru   r%   )r  rA   rU  r  ru   r|   NNNN)
r  r  r   r  r  r[   r  r[   ru   rA   NN)r  r  r  r  ru   rA   )r  r2   r  r  ru   rA   )Or   
__module____qualname____doc____annotations__ri   propertyr_   ra   rc   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r  r  __or____and__r   r   r   r   r   r   r   r:  r?  r   rT  r[  rb  rf  rh  rm  r   r   rw  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r!  __classcell__rr   s   @rs   rA   rA     s	        I IV  $-CG8<"/7# # # # # # #4    X ! ! ! X! ( ( ( X( & & & &L L L L. . . .         
    JO8 8 8 8 8Y Y Y Y Y    
 
 
 
    1 1 1 X1
 5 5 5 X5
 = = = X=
! ! ! !0H H HT
2 
2 
2 
20 0 0 0   % % % %   P P P P
 
 
 

- - - -
 
 
 

- - - -         
 
 
 

 
 
 
/ / / /
 FG   * 8<BF	"" "" "" "" ""L +/(,	    D FJ7;	$" $" $" $" $"N DI    . 8<    0 FK    0 +/      (+"%    X  +."%    X  .1"%    X  +..1(+"%    X +/.1i(,"&? ? ? ? ?B   * .2	: : : : :@ AE	    < @D	    41 1 1 1C C C C C "
 "
 "
 "
 "
H$ $ $ $> > > > >
    X   !	    X   !    X  !"%    X  JM!"%' ' ' ' X' JN""&A A A A AJ  $	

 

 

 

 

  "& $"&26,0R R R R Rn 2:19.2;?#'CU CU CU CU CUP ?G.2;?#'8O 8O 8O 8O 8OtP P P P P
 
 
 
   <' ' ' 'R   
, , , ,0* * * *0        &*!%#'"&# # # # #L MQ) ) ) ) )X JN> > > > > > > > > >rt   c                  T    e Zd ZU dZded<   	 	 	 dgdh fdZed             Zej        d             ZdidZ	e
	 djdkd            Ze
	 djdld            Ze
	 djdmd            Ze
	 djdnd            Ze
	 djdod"            Ze
	 djdpd$            Z	 djdpd%Zdqd&Zdrd*Ze
dsd.            Ze
dtd/            Zdud2Zdvd5Zdrd6Ze
	 dwdxd<            Ze
	 dwdyd?            Ze
	 dwdzdA            Z	 d{dzdBZ	 d{d|dDZ	 d{d}dGZd~dIZ	 d{ddLZddOZ	 	 dddSZddTZd{ddXZ	 	 	 	 	 	 ddddZddfZ xZS )rD   a9  A ConjunctiveGraph is an (unnamed) aggregation of all the named
    graphs in a store.

    !!! warning "Deprecation notice"
        ConjunctiveGraph is deprecated, use [`rdflib.graph.Dataset`][rdflib.graph.Dataset] instead.

    It has a `default` graph, whose name is associated with the
    graph throughout its life. Constructor can take an identifier
    to use as the name of this default graph or it will assign a
    BNode.

    All methods that add triples work against this default graph.

    All queries are carried out against the union of all graphs.
    r5   _default_contextr]   Nr_   r`   ra   $Optional[Union[IdentifiedNode, str]]default_graph_baser[   c                \   t          t          |                               ||           t          |           t          u rt	          j        dt          d           | j        j        s
J d            d| _        d| _	        t          | j        |pt                      |          | _        d S )Nra   z4ConjunctiveGraph is deprecated, use Dataset instead.   
stacklevelz9ConjunctiveGraph must be backed by a context aware store.Tr_   ra   r\   )rh   rD   ri   r   warningswarnDeprecationWarningr_   rX   rZ   rA   r(   rG  )rq   r_   ra   rI  rr   s       rs   ri   zConjunctiveGraph.__init__@  s     	%%..u.LLL::)))MF"    z' 	
 	
J	
 	
' "!.3*)>uwwEW/
 /
 /
rt   c                    | j         S rw   rG  rx   s    rs   r  z ConjunctiveGraph.default_contextX      $$rt   c                    || _         d S rw   rT  rq   r?  s     rs   r  z ConjunctiveGraph.default_context\       %rt   ru   r~   c                .    d}|| j         j        j        z  S )NzK[a rdflib:ConjunctiveGraph;rdflib:storage [a rdflib:Store;rdfs:label '%s']]r_   rr   r   rq   patterns     rs   r   zConjunctiveGraph.__str__`  s!    0 	 -666rt   Ftriple_or_quadrO   rW   c                    d S rw   r   rq   r]  r]   s      rs   _spoczConjunctiveGraph._spocg  s	    
 Crt   %Union[_TripleType, _OptionalQuadType]r7   c                    d S rw   r   r_  s      rs   r`  zConjunctiveGraph._spocn  	    
  Crt   r|   (Tuple[None, None, None, Optional[Graph]]c                    d S rw   r   r_  s      rs   r`  zConjunctiveGraph._spocu  s	    
 473rt   "Optional[_TripleOrQuadPatternType]r:   c                    d S rw   r   r_  s      rs   r`  zConjunctiveGraph._spoc|  s	    
 3rt   rT   r>   c                    d S rw   r   r_  s      rs   r`  zConjunctiveGraph._spoc  rc  rt   #Optional[_TripleOrQuadSelectorType]c                    d S rw   r   r_  s      rs   r`  zConjunctiveGraph._spoc  rc  rt   c                    |ddd|r| j         ndfS t          |          dk    r|r| j         nd}|\  }}}n/t          |          dk    r|\  }}}}|                     |          }||||fS )z_
        helper method for having methods that support
        either triples or quads
        N      )r  r  _graph)rq   r]  r]   r   r   r   r   s          rs   r`  zConjunctiveGraph._spoc  s     !$g&Od&:&:4PP~!##(/9$$TA&IQ11  A%%)LQ1aAA!Qzrt   c                x    |                      |          \  }}}}|                     |||f|          D ]} dS dS )z)Support for 'triple/quad in graph' syntaxr   TF)r`  r   )rq   r]  r   r   r   r   r  s          rs   r   zConjunctiveGraph.__contains__  sL    ZZ//
1aq!Qi33 	 	A44urt   rq   rC   rP   c                    |                      |d          \  }}}}t          |||           | j                            |||f|d           | S )zlAdd a triple or quad to the store.

        if a triple is given it is added to the default context
        Tr]   F)r   r   )r`  r   r_   r   rq   r]  r   r   r   r   s         rs   r   zConjunctiveGraph.add  sZ     ZZZ==
1aAq! 	
1ay!E:::rt   r   )Union[Graph, _ContextIdentifierType, str]rA   c                    d S rw   r   rq   r   s     rs   rn  zConjunctiveGraph._graph  s    MPSrt   c                    d S rw   r   ru  s     rs   rn  zConjunctiveGraph._graph  s    '*srt   3Optional[Union[Graph, _ContextIdentifierType, str]]r  c                \   |d S t          |t                    s|                     |          S t          |t          t          f          r|S 	 |                     |j                  }|J n*# t          $ r |                     |j                  }Y nw xY w|                    |           |S rw   )	rk   rA   get_contextrF   rD   	get_graphra   
IndexErrorr   )rq   r   rn  s      rs   rn  zConjunctiveGraph._graph  s     94!U## 	##A&&&!g'7899 <!^^AL99F!----! < < <!--al;;FFF<"""s   A- -$BBr   r   c                T      j                              fd|D                         S )z&Add a sequence of triples with contextc              3  v   K   | ]3\  }}}}t          |||          |||                    |          fV  4d S rw   )r   rn  r   s        rs   r   z(ConjunctiveGraph.addN.<locals>.<genexpr>  se       
 
*4!Q1QPQSTAUAU
1dkk!nn%
 
 
 
 
 
rt   r_   r   r   s   ` rs   r   zConjunctiveGraph.addN  sJ    
 	
 
 
 
 
8=
 
 
 	
 	
 	
 rt   c                x    |                      |          \  }}}}| j                            |||f|           | S )zRemoves a triple or quads

        if a triple is given it is removed from all contexts
        a quad is removed from the given context only
        r   )r`  r_   r   rr  s         rs   r   zConjunctiveGraph.remove  sC     ZZ//
1a
1a)Q///rt   .rS   r   r8  r   c                    d S rw   r   rq   r]  r   s      rs   r   zConjunctiveGraph.triples  s	    
 .1Srt   rR   r   c                    d S rw   r   r  s      rs   r   zConjunctiveGraph.triples  s	    
 25rt   r   c                    d S rw   r   r  s      rs   r   zConjunctiveGraph.triples  s	    
 :=rt   c              #    K   |                      |          \  }}}}|                     |p|          }| j        r|| j        k    rd}n	|| j        }t	          |t
                    r*|| }|                    |||          D ]\  }}|||fV  dS | j                            |||f|          D ]\  \  }}}}|||fV  dS )a
  Iterate over all the triples in the entire conjunctive graph

        For legacy reasons, this can take the context to query either
        as a fourth element of the quad, or as the explicit context
        keyword parameter. The kw param takes precedence.
        Nr   )	r`  rn  rZ   r  rk   r$   r   r_   r   )rq   r]  r   r   r   r   r   r   s           rs   r   zConjunctiveGraph.triples	  s      ZZ//
1a++gl++ 	/$....a 	w1--  1Ag  "&!3!3Q1Iw!3!O!O  	Aq2Ag rt   (Generator[_OptionalQuadType, None, None]c              #     K   |                      |          \  }}}}| j                            |||f|          D ]\  \  }}}}|D ]
}||||fV  dS )z:Iterate over all the quads in the entire conjunctive graphr   N)r`  r_   r   )rq   r]  r   r   r   r   r   ctxs           rs   r   zConjunctiveGraph.quads%	  s      
 ZZ//
1a!Z//Aq	1/EE 	# 	#MIQ1r # #Asl""""#	# 	#rt   r   r7  c              #     K   |\  }}}|| j         s| j        }n|                     |          }| j                            |||f|          D ]\  \  }}}}	|||fV  dS )z<Iterate over all the triples in the entire conjunctive graphNr   )rZ   r  rn  r_   r:  )
rq   r   r   r   r   r   s1p1o1r   s
             rs   r:  z ConjunctiveGraph.triples_choices0	  s       1a?% /.kk'**G !%
 : :Aq!9g : V V 	 	LRR"b"*	 	rt   r   c                4    | j                                         S )z1Number of triples in the entire conjunctive graph)r_   r   rx   s    rs   r   zConjunctiveGraph.__len__A	  s    z!!###rt   Optional[_TripleType]#Generator[_ContextType, None, None]c              #     K   | j                             |          D ]3}t          |t                    r|V  |                     |          V  4dS )z|Iterate over all contexts in the graph

        If triple is specified, iterate over all contexts the triple is in.
        N)r_   rM  rk   rA   ry  )rq   r   r   s      rs   rM  zConjunctiveGraph.contextsE	  so       z**622 	0 	0G'5)) 0  &&w//////	0 	0rt   r8   Union[Graph, None]c                P    fd|                                  D             d         S )z0Returns the graph identified by given identifierc                *    g | ]}|j         k    |S r   rK  )r   r  ra   s     rs   
<listcomp>z.ConjunctiveGraph.get_graph.<locals>.<listcomp>X	  s%    IIIaalj.H.H.H.H.Hrt   r   )rM  r  s    `rs   rz  zConjunctiveGraph.get_graphV	  s*    IIII4==??III!LLrt   rb   r   r\   c                <    t          | j        || j        |          S )zgReturn a context graph for the given identifier

        identifier must be a URIRef or BNode.
        )r_   ra   rc   r\   )rA   r_   rc   )rq   ra   r   r\   s       rs   ry  zConjunctiveGraph.get_contextZ	  s,     *!"4	
 
 
 	
rt   c                <    | j                             d|           dS )z(Removes the given context from the graphr   N)r_   r   )rq   r   s     rs   remove_contextzConjunctiveGraph.remove_contextk	  s!    
,g66666rt   r  
context_idr/   c                d    |                     dd          d         }|d}t          ||          S )zURI#context#r   r   Nz#context)r\   )splitr/   )rq   r  r  s      rs   r  zConjunctiveGraph.context_ido	  s8    iiQ"#Jjs++++rt   r  r  r  rz  r  r  r  r  r  r|  r   c                `    t          ||||||          }| j        } |j        |f||d| | S )a  Parse source adding the resulting triples to its own context (sub graph
        of this graph).

        See [`rdflib.graph.Graph.parse`][rdflib.graph.Graph.parse] for documentation on arguments.

        Args:
            source: The source to parse
            publicID: The public ID of the source
            format: The format of the source
            location: The location of the source
            file: The file object to parse
            data: The data to parse
            **args: Additional arguments

        Returns:
            The graph into which the source was parsed. In the case of n3 it returns
            the root context.

        Note:
            If the source is in a format that does not support named graphs its triples
            will be added to the default graph (i.e. ConjunctiveGraph.default_context).

        !!! warning "Caution"
            This method can access directly or indirectly requested network or
            file resources, for example, when parsing JSON-LD documents with
            `@context` directives that point to a network location.

            When processing untrusted or potentially malicious documents,
            measures should be taken to restrict network and file access.

            For information on available security measures, see the RDFLib
            Security Considerations documentation.

        !!! example "Changed in 7.0"
            The `publicID` argument is no longer used as the identifier (i.e. name)
            of the default graph as was the case before version 7.0. In the case of
            sources that do not support named graphs, the `publicID` parameter will
            also not be used as the name for the graph that the data is loaded into,
            and instead the triples from sources that do not support named graphs will
            be loaded into the default graph (i.e. ConjunctiveGraph.default_context).
        r  )r  rz  )r#   r  r  )	rq   r  r  rz  r  r  r  r|  r   s	            rs   r  zConjunctiveGraph.parsev	  s[    l %
 
 
" &fGxGG$GGGrt   r  c                ,    t           | j        | j        ffS rw   )rD   r_   ra   rx   s    rs   r  zConjunctiveGraph.__reduce__	  s    $*do!>>>rt   )r]   NN)r_   r`   ra   rH  rI  r[   r"  r#  )r]  rO   r]   rW   ru   rO   )r]  ra  r]   rW   ru   r7   )r]  r|   r]   rW   ru   rd  )r]  rf  r]   rW   ru   r:   )r]  rT   r]   rW   ru   r>   )r]  ri  r]   rW   ru   r>   r]  rT   ru   rW   )rq   rC   r]  rP   ru   rC   )r   rs  ru   rA   )r   r|   ru   r|   )r   rw  ru   r  )rq   rC   r   r   ru   rC   ).)r]  rS   r   r8  ru   r   )r]  rR   r   r8  ru   r   )r]  rT   r   r8  ru   r   rw   )r]  rf  ru   r  r*  r)  r   r  ru   r  )ra   r8   ru   r  )FN)ra   rb   r   rW   r\   r[   ru   rA   )r   r5   ru   r|   )r  r~   r  r[   ru   r/   r6  r7  r9  )r   r<  r=  r>  r?  ri   r@  r  rA  r   r   r`  r   r   rn  r   r   r   r   r:  r   rM  rz  ry  r  r  r  r  rD  rE  s   @rs   rD   rD   -  s           #""" $-;?,0	
 
 
 
 
 
 
0 % % X% & & &7 7 7 7      X          X   7 7 7 7 X7      X          X           X      *      " PPP XP*** X*   ,   	 	 	 	  +.1 1 1 1 X1  +.5 5 5 5 X5  +.= = = = X= +/    B DH	# 	# 	# 	# 	# +/    "$ $ $ $
 /30 0 0 0 0"M M M M "	
 
 
 
 
"7 7 7 7, , , , , "& $"&26,0I I I I IV? ? ? ? ? ? ? ?rt   zurn:x-rdflib:defaultc                      e Zd ZdZ	 	 	 dLdM fdZed             Zej        d             Zed             Zej        d             Ze fd            Z	dNdZ
dOdZdPdZdQdZdRdZ	 	 dSdTd$Z	 	 	 	 	 	 dUdVd0ZdWd2ZdXd3Z	 dYdZ fd7Z	 dYdZ fd8Z	 dYd[ fd<Zd\d=Zed]dA            Ze	 	 	 d^d]dC            Ze	 	 	 	 d_d`dD            Ze	 	 	 d^dadF            Ze	 	 	 	 d_dbdI            Z	 	 	 	 dcdb fdKZ xZS )drF   aj  
    An RDFLib Dataset is an object that stores multiple Named Graphs - instances of
    RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single
    Graph use.

    RDFLib's Dataset class is based on the [RDF 1.2. 'Dataset' definition](https://www.w3.org/TR/rdf12-datasets/):

    An RDF dataset is a collection of RDF graphs, and comprises:

    - Exactly one default graph, being an RDF graph. The default graph does not
        have a name and MAY be empty.
    - Zero or more named graphs. Each named graph is a pair consisting of an IRI or
        a blank node (the graph name), and an RDF graph. Graph names are unique
        within an RDF dataset.

    Accordingly, a Dataset allows for `Graph` objects to be added to it with
    [`URIRef`][rdflib.term.URIRef] or [`BNode`][rdflib.term.BNode] identifiers and always
    creats a default graph with the [`URIRef`][rdflib.term.URIRef] identifier
    `urn:x-rdflib:default`.

    Dataset extends Graph's Subject, Predicate, Object (s, p, o) 'triple'
    structure to include a graph identifier - archaically called Context - producing
    'quads' of s, p, o, g.

    Triples, or quads, can be added to a Dataset. Triples, or quads with the graph
    identifer :code:`urn:x-rdflib:default` go into the default graph.

    !!! warning "Deprecation notice"
        Dataset builds on the `ConjunctiveGraph` class but that class's direct
        use is now deprecated (since RDFLib 7.x) and it should not be used.
        `ConjunctiveGraph` will be removed from future RDFLib versions.

    Examples of usage and see also the `examples/datast.py` file:

    ```python
    >>> # Create a new Dataset
    >>> ds = Dataset()
    >>> # simple triples goes to default graph
    >>> ds.add((
    ...     URIRef("http://example.org/a"),
    ...     URIRef("http://www.example.org/b"),
    ...     Literal("foo")
    ... ))  # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>

    >>> # Create a graph in the dataset, if the graph name has already been
    >>> # used, the corresponding graph will be returned
    >>> # (ie, the Dataset keeps track of the constituent graphs)
    >>> g = ds.graph(URIRef("http://www.example.com/gr"))

    >>> # add triples to the new graph as usual
    >>> g.add((
    ...     URIRef("http://example.org/x"),
    ...     URIRef("http://example.org/y"),
    ...     Literal("bar")
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
    >>> # alternatively: add a quad to the dataset -> goes to the graph
    >>> ds.add((
    ...     URIRef("http://example.org/x"),
    ...     URIRef("http://example.org/z"),
    ...     Literal("foo-bar"),
    ...     g
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>

    >>> # querying triples return them all regardless of the graph
    >>> for t in ds.triples((None,None,None)):  # doctest: +SKIP
    ...     print(t)  # doctest: +NORMALIZE_WHITESPACE
    (rdflib.term.URIRef("http://example.org/a"),
     rdflib.term.URIRef("http://www.example.org/b"),
     rdflib.term.Literal("foo"))
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/z"),
     rdflib.term.Literal("foo-bar"))
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/y"),
     rdflib.term.Literal("bar"))

    >>> # querying quads() return quads; the fourth argument can be unrestricted
    >>> # (None) or restricted to a graph
    >>> for q in ds.quads((None, None, None, None)):  # doctest: +SKIP
    ...     print(q)  # doctest: +NORMALIZE_WHITESPACE
    (rdflib.term.URIRef("http://example.org/a"),
     rdflib.term.URIRef("http://www.example.org/b"),
     rdflib.term.Literal("foo"),
     None)
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/y"),
     rdflib.term.Literal("bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/z"),
     rdflib.term.Literal("foo-bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))

    >>> # unrestricted looping is equivalent to iterating over the entire Dataset
    >>> for q in ds:  # doctest: +SKIP
    ...     print(q)  # doctest: +NORMALIZE_WHITESPACE
    (rdflib.term.URIRef("http://example.org/a"),
     rdflib.term.URIRef("http://www.example.org/b"),
     rdflib.term.Literal("foo"),
     None)
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/y"),
     rdflib.term.Literal("bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/z"),
     rdflib.term.Literal("foo-bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))

    >>> # resticting iteration to a graph:
    >>> for q in ds.quads((None, None, None, g)):  # doctest: +SKIP
    ...     print(q)  # doctest: +NORMALIZE_WHITESPACE
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/y"),
     rdflib.term.Literal("bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))
    (rdflib.term.URIRef("http://example.org/x"),
     rdflib.term.URIRef("http://example.org/z"),
     rdflib.term.Literal("foo-bar"),
     rdflib.term.URIRef("http://www.example.com/gr"))
    >>> # Note that in the call above -
    >>> # ds.quads((None,None,None,"http://www.example.com/gr"))
    >>> # would have been accepted, too

    >>> # graph names in the dataset can be queried:
    >>> for c in ds.graphs():  # doctest: +SKIP
    ...     print(c.identifier)  # doctest:
    urn:x-rdflib:default
    http://www.example.com/gr
    >>> # A graph can be created without specifying a name; a skolemized genid
    >>> # is created on the fly
    >>> h = ds.graph()
    >>> for c in ds.graphs():  # doctest: +SKIP
    ...     print(c)  # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
    DEFAULT
    https://rdflib.github.io/.well-known/genid/rdflib/N...
    http://www.example.com/gr
    >>> # Note that the Dataset.graphs() call returns names of empty graphs,
    >>> # too. This can be restricted:
    >>> for c in ds.graphs(empty=False):  # doctest: +SKIP
    ...     print(c)  # doctest: +NORMALIZE_WHITESPACE
    DEFAULT
    http://www.example.com/gr

    >>> # a graph can also be removed from a dataset via ds.remove_graph(g)
    ```

    !!! example "New in version 4.0"
    r]   FNr_   r`   rZ   rW   rI  r[   c                    t          t          |                               |d            | j        j        st          d          t          | j        t          |          | _        || _	        d S )N)r_   ra   z.Dataset must be backed by a graph-aware store!rO  )
rh   rF   ri   r_   graph_aware	ExceptionrA   DATASET_DEFAULT_GRAPH_IDrG  rZ   )rq   r_   rZ   rI  rr   s       rs   ri   zDataset.__init__b
  sw     	gt%%Ed%CCCz% 	NLMMM %*/#!
 !
 !
 +rt   c                H    t          j        dt          d           | j        S NzIDataset.default_context is deprecated, use Dataset.default_graph instead.rL  rM  rP  rQ  rR  rG  rx   s    rs   r  zDataset.default_contextt
  s/    W	
 	
 	
 	

 $$rt   c                L    t          j        dt          d           || _        d S r  r  rW  s     rs   r  zDataset.default_context}
  s4    W	
 	
 	
 	

 !&rt   c                    | j         S rw   rT  rx   s    rs   default_graphzDataset.default_graph
  rU  rt   c                    || _         d S rw   rT  rW  s     rs   r  zDataset.default_graph
  rX  rt   c                p    t          j        dt          d           t          t          |           j        S )NzHDataset.identifier is deprecated and will be removed in future versions.rL  rM  )rP  rQ  rR  rh   rF   ra   )rq   rr   s    rs   ra   zDataset.identifier
  s:    V	
 	
 	
 	

 Wd##..rt   ru   r~   c                .    d}|| j         j        j        z  S )NzB[a rdflib:Dataset;rdflib:storage [a rdflib:Store;rdfs:label '%s']]rZ  r[  s     rs   r   zDataset.__str__
  s    S 	 -666rt   (Tuple[Type[Dataset], Tuple[Store, bool]]c                <    t          |           | j        | j        ffS rw   )r   r_   rZ   rx   s    rs   r  zDataset.__reduce__
  s    T

TZ);<==rt   8Tuple[Store, _ContextIdentifierType, _ContextType, bool]c                6    | j         | j        | j        | j        fS rw   r_   ra   r  rZ   rx   s    rs   __getstate__zDataset.__getstate__
  s    z4?D,>@RRRrt   stater|   c                <    |\  | _         | _        | _        | _        d S rw   r  )rq   r  s     rs   __setstate__zDataset.__setstate__
  s$    
 OTK
DOT%79K9K9Krt   rq   rE   r   r   c                D    |                      d |D                        | S )zMAdd all quads in Dataset other to Dataset.
        BNode IDs are not changed.c              3  ,   K   | ]\  }}}}||||fV  d S rw   r   )r   r   r   r   gs        rs   r   z#Dataset.__iadd__.<locals>.<genexpr>
  s2      77:1aA1aA,777777rt   r   r   s     rs   r   zDataset.__iadd__
  s*     			77777777rt   ra   :Optional[Union[_ContextIdentifierType, _ContextType, str]]r\   rA   c                    |Cddl m}m} |                     d||z   d           t	                                                      }|                     |          }||_        | j        	                    |           |S )Nr   )_SKOLEM_DEFAULT_AUTHORITYrdflib_skolem_genidgenidF)rp  )
rdflib.termr  r  r   r(   r  rn  r\   r_   	add_graph)rq   ra   r\   r  r  r  s         rs   graphzDataset.graph
  s    
 RRRRRRRRII),??    
 **,,JKK
##
Qrt   r  r  r  rz  r  r  r  r  r  r|  r   c           	     6    t          j        | ||||||fi | | S )a  Parse an RDF source adding the resulting triples to the Graph.

        Args:
            source: The source to parse. See rdflib.graph.Graph.parse for details.
            publicID: The public ID of the source.
            format: The format of the source.
            location: The location of the source.
            file: The file object to parse.
            data: The data to parse.
            **args: Additional arguments.

        Returns:
            The graph that the source was parsed into.

        Note:
            The source is specified using one of source, location, file or data.

        If the source is in a format that does not support named graphs its triples
        will be added to the default graph
        (i.e. :attr:`.Dataset.default_graph`).
            If the source is in a format that does not support named graphs its triples
            will be added to the default graph (i.e. Dataset.default_graph).

        !!! warning "Caution"
            This method can access directly or indirectly requested network or
            file resources, for example, when parsing JSON-LD documents with
            `@context` directives that point to a network location.

            When processing untrusted or potentially malicious documents,
            measures should be taken to restrict network and file access.

            For information on available security measures, see the RDFLib
            Security Considerations documentation.

        !!! example "Changed in 7.0"
            The `publicID` argument is no longer used as the identifier (i.e. name)
            of the default graph as was the case before version 7.0. In the case of
            sources that do not support named graphs, the `publicID` parameter will
            also not be used as the name for the graph that the data is loaded into,
            and instead the triples from sources that do not support named graphs will
            be loaded into the default graph (i.e. Dataset.default_graph).
        )rD   r  )rq   r  r  rz  r  r  r  r|  s           rs   r  zDataset.parse
  s=    n 	&(FHdD	
 	
DH	
 	
 	
 rt   r  c                ,    |                      |          S )zalias of graph for consistency)r  rq   r  s     rs   r  zDataset.add_graph  s     zz!}}rt   c                    t          |t                    s|                     |          }| j                            |           ||| j        k    r| j                            | j                   | S rw   )rk   rA   ry  r_   remove_graphr  r  r  s     rs   r  zDataset.remove_graph	  sq     !U## 	$  ##A
"""9T/// J  !3444rt   r   r  r  c              #    K   t          j        dt          d           d}t          t          |                               |          D ]}||j        t          k    z  }|V  |s|                     t                    V  d S d S )Nz;Dataset.contexts is deprecated, use Dataset.graphs instead.rL  rM  F)	rP  rQ  rR  rh   rF   rM  ra   r  r  rq   r   r]   r   rr   s       rs   rM  zDataset.contexts  s       	I	
 	
 	
 	

 w%%..v66 	 	Aq|'???GGGGG 	7**56666666	7 	7rt   c              #     K   d}t          t          |                               |          D ]}||j        t          k    z  }|V  |s|                     t                    V  d S d S rg   )rh   rF   rM  ra   r  r  r  s       rs   graphszDataset.graphs%  s       w%%..v66 	 	Aq|'???GGGGG 	7**56666666	7 	7rt   quadrf  2Generator[_OptionalIdentifiedQuadType, None, None]c              #     K   t          t          |                               |          D ]-\  }}}}|j        | j        k    r	|||d fV   ||||j        fV  .d S rw   )rh   rF   r   ra   r  )rq   r  r   r   r   r   rr   s         rs   r   zDataset.quads0  s        ..44T:: 	, 	,JAq!Q|t111Atm#### Aq|+++++	, 	,rt   c                ,    |                      d          S )z$Iterates over all quads in the storer:  )r   rx   s    rs   r   zDataset.__iter__<  s     zz2333rt   ry  r{  r}  c                    d S rw   r   r  s         rs   r  zDataset.serializeB  r  rt   .c                   d S rw   r   r  s         rs   r  zDataset.serializeM  r  rt   c                    d S rw   r   r  s         rs   r  zDataset.serializeY  r  rt   r  c                    d S rw   r   r  s         rs   r  zDataset.serialized  r  rt   r  r  c                    d S rw   r   r  s         rs   r  zDataset.serializeo  r  rt   trigc                N     t          t          |           j        d||||d|S )N)ry  rz  r\   r{  r   )rh   rF   r  )rq   ry  rz  r\   r{  r|  rr   s         rs   r  zDataset.serializey  sA     .uWd##- 
#F
 
TX
 
 	
rt   )r]   FN)r_   r`   rZ   rW   rI  r[   r"  )ru   r  )ru   r  )r  r  ru   r|   )rq   rE   r   r   ru   rE   r;  )ra   r  r\   r[   ru   rA   r6  )r  r  r  r[   rz  r[   r  r[   r  r  r  r  r|  r   ru   rF   )r  r  ru   rA   )rq   rE   r  r  ru   rE   rw   r  )r  rf  ru   r  )ru   r  r0  r1  r2  r3  r4  r5  )Nr  NN)r   r<  r=  r>  ri   r@  r  rA  r  ra   r   r  r  r  r   r  r  r  r  rM  r  r   r   r   r  rD  rE  s   @rs   rF   rF   	  s       W Wv $-#,0	+ + + + + + +$ % % X% & & & % % X% & & & / / / / X/7 7 7 7> > > >S S S ST T T T    RV"    2 "& $"&26,0: : : : :x       /37 7 7 7 7 7 7  /37 7 7 7 7 7 7 :>	, 	, 	, 	, 	, 	, 	,4 4 4 4    X   !	    X   !    X  !"%    X  JM!"%' ' ' ' X' JN""&

 

 

 

 

 

 

 

 

 

 

rt   c                  N     e Zd ZdZd fdZddZddZdddZddZddZ	 xZ
S )rH   a  
    Quoted Graphs are intended to implement Notation 3 formulae. They are
    associated with a required identifier that the N3 parser *must* provide
    in order to maintain consistent formulae identification for scenarios
    such as implication and other such processing.
    r_   r`   ra   rb   c                Z    t          t          |                               ||           d S rw   )rh   rH   ri   )rq   r_   ra   rr   s      rs   ri   zQuotedGraph.__init__  s+    
 	k4  ))%<<<<<rt   rq   r@   r   r6   ru   c                $   |\  }}}t          |t                    sJ d|d            t          |t                    sJ d|d            t          |t                    sJ d|d            | j                            |||f| d           | S )z!Add a triple with self as contextr   r   r   r   Tr   )rk   r-   r_   r   r   s        rs   r   zQuotedGraph.add  s    1a!T""NNN111$NNN"!T""PPPQQQ$PPP"!T""MMM!!!$MMM"
1ay$t444rt   r   r   c                T      j                              fd|D                         S )r   c              3     K   | ]C\  }}}}t          |t                    r'|j        j        u *t          |||          ;||||fV  Dd S rw   )rk   rH   ra   r   r   s        rs   r   z#QuotedGraph.addN.<locals>.<genexpr>  sx       
 
1a![))
 //Aq!$$ 0 1aL 0///	
 
rt   r~  r   s   ` rs   r   zQuotedGraph.addN  sJ     	
 
 
 
 
#
 
 
 	
 	
 	
 rt   Nrc   rd   r~   c                >    d| j                             |          z  S )r  z{%s}r  r  r  s     rs   r   zQuotedGraph.n3  r  rt   c                h    | j                                         }| j        j        j        }d}|||fz  S )NzK{this rdflib.identifier %s;rdflib:storage [a rdflib:Store;rdfs:label '%s']})ra   r   r_   rr   r   )rq   ra   labelr\  s       rs   r   zQuotedGraph.__str__  s>    _''))

$-0 	 *e,,,rt   r  c                ,    t           | j        | j        ffS rw   )rH   r_   ra   rx   s    rs   r  zQuotedGraph.__reduce__  s    TZ999rt   )r_   r`   ra   rb   r$  r%  rw   r8  r"  r9  )r   r<  r=  r>  ri   r   r   r   r   r  rD  rE  s   @rs   rH   rH     s         = = = = = =   
 
 
 
P P P P P- - - -: : : : : : : :rt   rH      c                  :    e Zd ZdZddZddZdd
ZddZddZdS )rI   a  Wrapper around an RDF Seq resource

    It implements a container type in Python with the order of the items
    returned corresponding to the Seq content. It is based on the natural
    ordering of the predicate names _1, _2, _3, etc, which is the
    'implementation' of a sequence in RDF terms.

    Args:
        graph: the graph containing the Seq
        subject:the subject of a Seq. Note that the init does not
            check whether this is a Seq, this is done in whoever
            creates this instance!
    r  rA   r  r2   c                x   |  t                      x}| _        t          t          t                    dz             }|                    |          D ]T\  }}|                    |          r:t          |                    |d                    }|	                    ||f           U|
                                 d S )N_r  )r   _listr/   r~   r   r   
startswithr   rq  r  sort)rq   r  r  r  LI_INDEXr   r   is           rs   ri   zSeq.__init__  s    1!VV#
#c((S.))++G44 	% 	%DAq||H%% %		(B//00aV$$$ 	

rt   ru   c                    | S rw   r   rx   s    rs   r   zSeq.toPython  r   rt   r)  c              #  ,   K   | j         D ]	\  }}|V  
dS )z#Generator over the items in the SeqN)r  )rq   r  r   s      rs   r   zSeq.__iter__  s0      z 	 	GAtJJJJ	 	rt   r   c                *    t          | j                  S )zLength of the Seq)r  r  rx   s    rs   r   zSeq.__len__  s    4:rt   r4   c                @    | j                             |          \  }}|S )z Item given by index from the Seq)r  r   )rq   indexr   s      rs   r   zSeq.__getitem__  s     j,,U33trt   N)r  rA   r  r2   )ru   rI   )ru   r)  r)  )ru   r4   )	r   r<  r=  r>  ri   r   r   r   r   r   rt   rs   rI   rI     s                  
        rt   rI   c                      e Zd ZddZddZdS )	rJ   ru   r|   c                    d S rw   r   rx   s    rs   ri   zModificationException.__init__      rt   r~   c                    	 dS )NzZModifications and transactional operations not allowed on ReadOnlyGraphAggregate instancesr   rx   s    rs   r   zModificationException.__str__  s    /	
 	
rt   Nru   r|   r"  r   r<  r=  ri   r   r   rt   rs   rJ   rJ     s<           
 
 
 
 
 
rt   rJ   c                      e Zd ZddZddZdS )	rK   ru   r|   c                    d S rw   r   rx   s    rs   ri   z&UnSupportedAggregateOperation.__init__  r  rt   r~   c                    dS )NzCThis operation is not supported by ReadOnlyGraphAggregate instancesr   rx   s    rs   r   z%UnSupportedAggregateOperation.__str__  s    WWrt   Nr  r"  r  r   rt   rs   rK   rK     sB           X X X X X Xrt   rK   c                  T    e Zd ZdZdWdX fdZdYd
ZdZdZd[dZd[dZd\d]dZ	d^dZ
d_dZd`dZd_dZedad             Zedbd#            Zedcd&            Zdcd'Zddd*Zded,Zdfd.Zd[d/Zdfd0Zdgd5Zdgd6Z	 dhdid;Zdjd=ZdkdldAZ	 dkdmdGZdndIZdodpdLZ	 	 dqdrdRZdhdsdUZd[dVZ xZ S )trL   zUtility class for treating a set of graphs as a single graph

    Only read operations are supported (hence the name). Essentially a
    ConjunctiveGraph over an explicit subset of the entire store.
    r]   r  List[Graph]r_   Union[str, Store]c                   |Jt          t          |                               |           t                              | |           d | _        t          |t                    r|rd |D             s
J d            || _        d S )Nc                <    g | ]}t          |t                    |S r   )rk   rA   r   r  s     rs   r  z3ReadOnlyGraphAggregate.__init__.<locals>.<listcomp>  s'    ;;;qjE&:&:;;;;rt   z*graphs argument must be a list of Graphs!!)rh   rL   ri   rA   *_ReadOnlyGraphAggregate__namespace_managerrk   r   r  )rq   r  r_   rr   s      rs   ri   zReadOnlyGraphAggregate.__init__  s    ($//88???NN4''''+D$ vt$$	8	8 <;F;;;	8 	8 8		8 	8< rt   ru   r~   c                0    dt          | j                  z  S )Nz#<ReadOnlyGraphAggregate: %s graphs>)r  r  rx   s    rs   r   zReadOnlyGraphAggregate.__repr__  s    4s4;7G7GGGrt   r   r   c                    t                      rw   rJ   r   s     rs   r   zReadOnlyGraphAggregate.destroy      #%%%rt   c                    t                      rw   r  rx   s    rs   r   zReadOnlyGraphAggregate.commit!  r  rt   c                    t                      rw   r  rx   s    rs   r   zReadOnlyGraphAggregate.rollback$  r  rt   Fstr | tuple[str, str]r   rW   r|   c                H    | j         D ]}|                    | ||           d S rw   )r  r   )rq   r   r   r  s       rs   r   zReadOnlyGraphAggregate.open'  s8    [ 	4 	4E JJt]F3333		4 	4rt   c                B    | j         D ]}|                                 d S rw   )r  r   )rq   r  s     rs   r   zReadOnlyGraphAggregate.close0  s,    [ 	 	EKKMMMM	 	rt   r   rP   c                    t                      rw   r  r   s     rs   r   zReadOnlyGraphAggregate.add4  r  rt   r   r   c                    t                      rw   r  r   s     rs   r   zReadOnlyGraphAggregate.addN7  r  rt   c                    t                      rw   r  r   s     rs   r   zReadOnlyGraphAggregate.remove;  r  rt   r9   r   c                    d S rw   r   r   s     rs   r   zReadOnlyGraphAggregate.triples?  r   rt   r;   r   c                    d S rw   r   r   s     rs   r   zReadOnlyGraphAggregate.triplesE  r   rt   r=   r   c                    d S rw   r   r   s     rs   r   zReadOnlyGraphAggregate.triplesK  r   rt   c              #     K   |\  }}}| j         D ]b}t          |t                    r%|                    | ||          D ]\  }}|||fV  <|                    |||f          D ]\  }}}|||fV  cd S rw   )r  rk   r$   r   r   )	rq   r   r   r   r   r  r  r  r  s	            rs   r   zReadOnlyGraphAggregate.triplesQ  s       1a[ 	% 	%E!T"" %FF4A.. " "DAqQ'MMMM" #(--Aq	":": % %JBBb"*$$$$%	% 	%rt   r]  rT   c                    d }t          |          dk    r|d         }| j        D ]#}||j        |j        k    r|d d         |v r dS $dS )Nrm  rl  TF)r  r  ra   )rq   r]  r   r  s       rs   r   z#ReadOnlyGraphAggregate.__contains__^  sk    ~!##$Q'G[ 	  	 E%"2g6H"H"H!"1"%..44urt   bGenerator[Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType], None, None]c              #  6  	K   d	t          |          dk    r|\  }}}	n|\  }}}	?	fd| j        D             D ])}|                    |||f          D ]\  }}}||||fV  *dS | j        D ])}|                    |||f          D ]\  }}}||||fV  *dS )z8Iterate over all the quads in the entire aggregate graphNrm  c                     g | ]
}|k    |S r   r   )r   r  r   s     rs   r  z0ReadOnlyGraphAggregate.quads.<locals>.<listcomp>{  s    ;;;AFF!FFFrt   )r  r  r   )
rq   r]  r   r   r   r  r  r  r  r   s
            @rs   r   zReadOnlyGraphAggregate.quadsj  s      ~!##'JAq!QQ %GAq!=;;;;T[;;; , ,"'--Aq	":": , ,JBBb"e+++++,, ,  , ,"'--Aq	":": , ,JBBb"e+++++,, ,rt   r   c                >    t          d | j        D                       S )Nc              3  4   K   | ]}t          |          V  d S rw   )r  r  s     rs   r   z1ReadOnlyGraphAggregate.__len__.<locals>.<genexpr>  s(      //a3q66//////rt   )sumr  rx   s    rs   r   zReadOnlyGraphAggregate.__len__  s!    //4;//////rt   c                    t                      rw   rK   rx   s    rs   r   zReadOnlyGraphAggregate.__hash__      +---rt   c                    |dS t          |t                    rdS t          |t                    r!| j        |j        k    | j        |j        k     z
  S dS )Nr   )rk   rA   rL   r  r   s     rs   r   zReadOnlyGraphAggregate.__cmp__  sX    =2u%% 	2566 	K%,.4;3MNN2rt   rq   r@   r   r   c                    t                      rw   r  r   s     rs   r   zReadOnlyGraphAggregate.__iadd__  r  rt   c                    t                      rw   r  r   s     rs   r   zReadOnlyGraphAggregate.__isub__  r  rt   Nr7  r   r8  c              #  z   K   |\  }}}| j         D ]*}|                    |||f          }|D ]\  }}	}
||	|
fV  +d S rw   )r  r:  )rq   r   r   r  r  r  r  choicesr   r   r   s              rs   r:  z&ReadOnlyGraphAggregate.triples_choices  sv      
 '-#G[ 	 	E ++Wi,IJJG"  1aAg		 	rt   r  c                    t          | d          r!| j        r| j                            |          S t                      Nrc   )r  rc   rh  rK   ri  s     rs   rh  zReadOnlyGraphAggregate.qname  sB    4,-- 	5$2H 	5)//444+---rt   Trj  rk  c                    t          | d          r"| j        r| j                            ||          S t                      r  )r  rc   rm  rK   rn  s      rs   rm  z$ReadOnlyGraphAggregate.compute_qname  sF    4,-- 	G$2H 	G)77XFFF+---rt   r  r[   ro  r   rp  c                    t                      rw   r  )rq   r  ro  rp  s       rs   r   zReadOnlyGraphAggregate.bind  s     ,---rt   rs  c              #     K   t          | d          r'| j                                        D ]\  }}||fV  d S | j        D ]"}|                                D ]\  }}||fV  #d S r  )r  rc   r   r  )rq   r  ro  r  s       rs   r   z!ReadOnlyGraphAggregate.namespaces  s      4,-- 	,%)%;%F%F%H%H ( (!	i'''''( (  , ,).)9)9);); , ,%FI )+++++,, ,rt   r   ru  c                    t                      rw   r  rx  s      rs   rw  z!ReadOnlyGraphAggregate.absolutize  r  rt   r  r  r  rz  r|  c                    t                      rw   r  )rq   r  r  rz  r|  s        rs   r  zReadOnlyGraphAggregate.parse  s     $%%%rt   rc   rd   c                    t                      rw   r  r  s     rs   r   zReadOnlyGraphAggregate.n3  r  rt   c                    t                      rw   r  rx   s    rs   r  z!ReadOnlyGraphAggregate.__reduce__  r  rt   rq  )r  r  r_   r  r"  )r   r~   ru   r   )ru   r   r#  )r   r  r   rW   ru   r|   r  )r   rP   ru   r   )r   r   ru   r   r&  r'  r(  r  )r]  rT   ru   r  r)  )rq   r@   r   r   ru   r   rw   r*  r+  r,  r-  )r  r[   ro  r   rp  rW   ru   r   r.  r/  )r  r~   ru  r   ru   r   r;  )
r  r  r  r[   rz  r[   r|  r   ru   r   )rc   rd   ru   r   )!r   r<  r=  r>  ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r:  rh  rm  r   r   rw  r  r   r  rD  rE  s   @rs   rL   rL     s              H H H H& & & && & & && & & &4 4 4 4 4   & & & && & & && & & & 1 1 1 X1
 5 5 5 X5
 = = = X=
% % % %	 	 	 	, , , ,20 0 0 0. . . .   & & & && & & & +/    . . . .
. . . . . GK. . . . .
, , , ,. . . . . #' $	& 	& 	& 	& 	&. . . . .. . . . . . . .rt   rL   termsr-   ru   te.Literal[True]c                     d S rw   r   r$  s    rs   r   r     s    363rt   r   rW   c                     d S rw   r   r'  s    rs   r   r     s    &)crt   c                 V    | D ]%}t          |t                    sJ d|d            &dS )NzTerm r   T)rk   r-   )r$  r  s     rs   r   r     sC     L L!T""KKK$KKK"K4rt   c                  D    e Zd ZdZddd
ZddZddZddZddZddZ	dS )rM   a?  Wrapper around graph that turns batches of calls to Graph's add
    (and optionally, addN) into calls to batched calls to addN`.

    Args:
        graph: The graph to wrap
        batch_size: The maximum number of triples to buffer before passing to
            Graph's addN
        batch_addn: If True, then even calls to `addN` will be batched according to
            batch_size

    Attributes:
        graph: The wrapped graph
        count: The number of triples buffered since initialization or the last call to reset
        batch: The current buffer of triples
      Fr  rA   
batch_sizer   
batch_addnrW   c                    |r|dk     rt          d          || _        |f| _        || _        || _        |                                  d S )NrL  z$batch_size must be a positive number)rR  r  _BatchAddGraph__graph_tuple_BatchAddGraph__batch_size_BatchAddGraph__batch_addnreset)rq   r  r,  r-  s       rs   ri   zBatchAddGraph.__init__  sT     	EZ!^^CDDD
#X&&

rt   ru   c                "    g | _         d| _        | S )zQ
        Manually clear the buffered triples and reset the count to zero
        r   )batchcountrx   s    rs   r2  zBatchAddGraph.reset  s     ')

rt   r]  Union[_TripleType, _QuadType]c                L   t          | j                  | j        k    r&| j                            | j                   g | _        | xj        dz  c_        t          |          dk    r#| j                            || j        z              n| j                            |           | S )zAdd a triple to the buffer.

        Args:
            triple_or_quad: The triple or quad to add

        Returns:
            The BatchAddGraph instance
        r   rl  )r  r4  r0  r  r   r5  r  r/  )rq   r]  s     rs   r   zBatchAddGraph.add  s     tz??d///JOODJ'''DJ

a

~!##Jnt/AABBBB Jn---rt   r   r   c                ~    | j         r|D ]}|                     |           n| j                            |           | S rw   )r1  r   r  r   )rq   r   qs      rs   r   zBatchAddGraph.addN"  sM     	#   JOOE"""rt   c                .    |                                   | S rw   )r2  rx   s    rs   	__enter__zBatchAddGraph.__enter__*  s    

rt   r|   c                X    |d         !| j                             | j                   d S d S )Nr   )r  r   r4  )rq   excs     rs   __exit__zBatchAddGraph.__exit__.  s.    q6>JOODJ''''' >rt   N)r+  F)r  rA   r,  r   r-  rW   )ru   rM   )r]  r6  ru   rM   )r   r   ru   rM   r  )
r   r<  r=  r>  ri   r2  r   r   r;  r>  r   rt   rs   rM   rM     s                    6      ( ( ( ( ( (rt   rM   )r$  r-   ru   r%  )r$  r   ru   rW   )zr>  
__future__r   loggingr  r  rP  ior   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   urllib.parser   urllib.requestr   rdflib.exceptionsrH  rdflib.namespacero  rdflib.pluginrl   rdflib.queryr  rdflib.utilr^   rdflib.collectionr   r   r   r   r    rdflib.parserr!   r"   r#   rdflib.pathsr$   rdflib.resourcer%   rdflib.serializerr&   rdflib.storer'   r  r(   r)   r*   r+   r,   r-   r.   r/   typing_extensionsterdflib.plugins.sparql.sparqlr0   r1   r2   r3   r4   r8   r6   rO   r7   rP   rN   r9   r;   r:   r<   rS   rR   r=   r>   rT   r?   rQ   r7  r@   rC   rE   rdflib._type_checkingrG   	getLoggerr   r  __all__rU   rA   r5   rD   r  rF   rH   term	_ORDERINGrI   r  rJ   rK   rL   r   rM   r   rt   rs   <module>rX     s  J JX # " " " " "                                                     , " ! ! ! ! ! ' ' ' ' ' ' & & & & & & $ $ $ $ $ $                 ( ( ( ( ( ( ) ) ) ) ) ) = = = = = = = = = = B B B B B B B B B B       $ $ $ $ $ $ ( ( ( ( ( (      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  ;""""::::::::' CDQR	$mXn5MM  ""DE #$mX>V5WW  ^h'78(=:QQ  x7x?VVW ^]^  ^]^  !!IJ $%UV ^U+,-] 
 ^U+,-]^  ""LM m;< @A 	$|
h~68M
MN	(<
 $~"68M
MN	(<
 (>":D<M
MNP  ')7
+
+
+W19KLLL GKy111	 w  y :999999		8	$	$! ! !H ')


p p p p pD p p pf3 U? U? U? U? U?u U? U? U?p "6"899 {
 {
 {
 {
 {
 {
 {
 {
|3: 3: 3: 3: 3:% 3: 3: 3:t &( k "- - - - - - - -`
 
 
 
 
I 
 
 
X X X X XI X X XN. N. N. N. N.- N. N. N.b 
 6 6 6 
 6 
 ) ) ) 
 )   K( K( K( K( K( K( K( K( K( K(rt   