
    4YshoE                       d dl mZmZmZmZmZmZmZmZm	Z	m
Z
 d dlZd dlmZ d dlZd dlmZmZ d dlmZmZmZmZ d dlZd dl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$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.Z.d dl/Z/d dl0Z0d dl1Z1d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 esJ esJ  ejp                  e9      Z:eeef   Z;e
eeeee;   f   Z<dZ=g dZ> G d de      Z? G d de?      Z@ ed      ZA G d de@      ZB G d de?      ZCdej                  j                  eC<    G d deF      ZG G d  d!eH      ZI G d" d#eH      ZJ G d$ d%e@      ZKd& ZL G d' d(eF      ZMd) ZNe9d*k(  r eN        yy)+    )
IOAnyIterableOptionalUnionTypecastoverload	GeneratorTupleN)warn)	NamespaceRDF)plugin
exceptionsquery	namespace)BNodeNodeURIRefLiteralGenid)Path)Store)
Serializer)Parsercreate_input_source)NamespaceManager)Resource
Collection)ParserError)BytesIO)urlparse)url2pathnamea%  
RDFLib defines the following kinds of Graphs:

* :class:`~rdflib.graph.Graph`
* :class:`~rdflib.graph.QuotedGraph`
* :class:`~rdflib.graph.ConjunctiveGraph`
* :class:`~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 :class:`~rdflib.graph.Graph`

Conjunctive Graph
-----------------

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
:class:`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 :class:`BNode`
for an identifier - if one isn't given.

see :class:`~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 :class:`~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 :class:`~rdflib.graph.Dataset`

Working with graphs
===================

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

    >>> 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 -
<http://rdflib.net>:

    >>> g = Graph('Memory', URIRef("http://rdflib.net"))
    >>> g.identifier
    rdflib.term.URIRef('http://rdflib.net')
    >>> str(g)  # doctest: +NORMALIZE_WHITESPACE
    "<http://rdflib.net> 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":

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

    >>> 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("http://rdflib.net/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 :meth:`~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.

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

    >>> 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('http://rdflib.net/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('http://rdflib.net/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('http://rdflib.net/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 :meth:`~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:

    >>> 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

    >>> 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 <http://rdflib.net/store#ConjunctiveGraph>;
    ...   rdf:predicate rdfs:label;
    ...   rdf:object "Conjunctive Graph" ] .
    ... '''
    >>> g2 = g2.parse(data=src, format="n3")
    >>> print(len(g2))
    4

Using Namespace class:

    >>> RDFLib = Namespace("http://rdflib.net/")
    >>> RDFLib.ConjunctiveGraph
    rdflib.term.URIRef('http://rdflib.net/ConjunctiveGraph')
    >>> RDFLib["Graph"]
    rdflib.term.URIRef('http://rdflib.net/Graph')

)	GraphConjunctiveGraphQuotedGraphSeqModificationExceptionDatasetUnSupportedAggregateOperationReadOnlyGraphAggregateBatchAddGraphc                       e Zd ZdZ	 	 	 	 dcdeeef   deeeef      dee	   dee   f fdZ
d Z ee      Zd	 Z ee      Zd
 Zd Z eeed      Zd Zd Zd Zd Zd Zd ZdddZdddZdeeeef   fdZdeeeeeef      fdZd Z deee   ede!ef   ee   f   fdZ"d Z#d Z$d Z%d Z&d  Z'd! Z(d" Z)d# Z*d$ Z+d% Z,d& Z-d' Z.d( Z/d) Z0d* Z1d+ Z2d, Z3e0Z4e1Z5d- Z6ded.ee   fd/Z7ded.ee   fd0Z8ded.ee   fd1Z9dfd2Z:dfd3Z;dfd4Z<dfd5Z=de>j~                  ddd6fd7Z?dgd8Z@ddeAj                  j                  eAj                  j                  ffd9ZEdgd:ZFd; ZGdfd<ZHdfd=ZIdfd>ZJd? ZKd@ ZLdhdAZMdidBZNdC ZOdjdDZPeQdEddFedee   dGed.eRf
dH       ZSeQ	 	 	 dkdEddFedee   dGed.eRf
dI       ZSeQ	 	 	 	 dldEddFedee   dGdd.ef
dJ       ZSeQ	 	 	 dkdEeeeTj                  eVeR   f   dFedee   dGee   d.d f
dK       ZSeQ	 	 	 	 dldEeeeeTj                  eVeR   f      dFedee   dGee   d.eeRed f   f
dL       ZS	 	 	 	 dmdEeeeeTj                  eVeR   f      dFedee   dGee   dMed.eeRed f   fdNZSdndOZW	 	 	 	 	 	 dodFee   dPeeeeReXf      fdQZYdpdRZZ	 	 	 	 	 dqdSeee[j                  f   dTeee]e[j                     f   dUe_d.e[j                  fdVZ[	 	 	 	 drdWZ`dX ZadY ZbdZ Zcd[ Zdd\ Zed] Zfd^ Zgd_ Zhdsd`ZidedaZjdb Zk xZlS )tr&   aw  An RDF Graph

    The constructor accepts one argument, the "store"
    that will be used to store the graph data (see the "store"
    package for stores currently shipped with rdflib).

    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.

    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: http://www.w3.org/2004/03/trix/
    Nstore
identifiernamespace_managerbasec                    t         t        |           || _        |  |xs
 t	               | _        t        | j
                  t              st        | j
                        | _        |  t        |t              s' t        j                  |t                     x| _        }n|| _        || _        d| _        d| _        d| _        y NF)superr&   __init__r3   r   _Graph__identifier
isinstancer   r   r   r   get_Graph__store_Graph__namespace_managercontext_awareformula_awaredefault_union)selfr0   r1   r2   r3   	__class__s        l/var/www/sten-cake5-migrate2.hellocrow.space/lexinfo-master/env/lib/python3.12/site-packages/rdflib/graph.pyr7   zGraph.__init__G  s     	eT#%	&1%'$++T2 &t'8'8 9D%'#;6::eU#;#==DL5 DL#4 """    c                     | j                   S N)r;   r@   s    rB   __get_storezGraph.__get_store_  s    ||rC   c                     | j                   S rE   )r8   rF   s    rB   __get_identifierzGraph.__get_identifierd  s       rC   c                 R    | j                   t        |       | _         | j                   S rE   )r<   r   rF   s    rB   _get_namespace_managerzGraph._get_namespace_manageri  s'    ##+'7'=D$'''rC   c                     || _         y rE   )r<   )r@   nms     rB   _set_namespace_managerzGraph._set_namespace_managern  s
    #% rC   zthis graph's namespace-manager)docc                 :    d| j                   dt        |       dS )Nz<Graph identifier=z (z)>)r1   typerF   s    rB   __repr__zGraph.__repr__w  s    /3T
KKrC   c                     t        | j                  t              r>| j                  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']].)r9   r1   r   n3r0   rA   __name__rF   s    rB   __str__zGraph.__str__z  sc    doov. ##%tzz';';'D'DF F
 W

$$--. .rC   c                     | S rE    rF   s    rB   toPythonzGraph.toPython      rC   c                 <    | j                   j                  |       | S )z<Destroy the store identified by `configuration` if supported)r;   destroyr@   configurations     rB   r\   zGraph.destroy  s    ]+rC   c                 :    | j                   j                          | S )zCommits active transactions)r;   commitrF   s    rB   r`   zGraph.commit  s    rC   c                 :    | j                   j                          | S )zRollback active transactions)r;   rollbackrF   s    rB   rb   zGraph.rollback  s    rC   c                 :    | j                   j                  ||      S )zOpen the graph store

        Might be necessary for stores that require opening a connection to a
        database or acquiring some resource.
        )r;   open)r@   r^   creates      rB   rd   z
Graph.open  s     ||  77rC   c                 :    | j                   j                  |      S )zClose the graph store

        Might be necessary for stores that require closing a connection to a
        database or releasing some resource.
        )commit_pending_transaction)r;   close)r@   rg   s     rB   rh   zGraph.close  s     ||!!=W!XXrC   triplec                     |\  }}}t        |t              sJ d|d       t        |t              sJ d|d       t        |t              sJ d|d       | j                  j                  |||f| d       | S )!Add a triple with self as contextSubject  must be an rdflib term
Predicate Object Fquoted)r9   r   r;   addr@   ri   spos        rB   rr   z	Graph.add  sy    1a!T"N1$NN"!T"PQ$PP"!T"M!$MM"!QD7rC   quadsc                 P      j                   j                   fd|D                S )%Add a sequence of triple with contextc              3      K   | ]D  \  }}}}t        |t              r-|j                  j                  u rt        |||      r||||f F y wrE   )r9   r&   r1   _assertnode.0rt   ru   rv   cr@   s        rB   	<genexpr>zGraph.addN.<locals>.<genexpr>  sO      
1a!U#/Aq!$	 1aL
   A
A)r;   addNr@   rw   s   ` rB   r   z
Graph.addN  s+     	 
#
 	
 rC   c                 @    | j                   j                  ||        | S )zRemove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
        context)r;   remover@   ri   s     rB   r   zGraph.remove  s      	FD1rC   c              #      K   |\  }}}t        |t              r#|j                  | ||      D ]  \  }}|||f  y| j                  j	                  |||f|       D ]  \  \  }}}}|||f  yw)zGenerator over the triple store

        Returns triples that match the given triple pattern. If triple pattern
        does not provide a context, all contexts will be searched.
        r   N)r9   r   evalr;   triples)r@   ri   rt   ru   rv   _s_ocgs           rB   r   zGraph.triples  s      1aa&&q!,  B!Ri  "&!5!5q!Qi!5!N 	Aq2Ags   A.A0c                    t        |t              r|j                  |j                  |j                  }}}|||| j                  |||f      S ||| j                  |      S ||| j                  |      S ||| j                  |      S || j                  ||      S || j                  ||      S || j                  ||      S |||f| v S t        |t        t        f      r| j                  |      S t        d      )aN  
        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

        >>> 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.

        .. versionadded:: 4.0

        zWYou can only index a graph by a single rdflib term or path, or a slice of rdflib terms.)r9   slicestartstopstepr   subject_predicatessubject_objectspredicate_objectssubjects
predicatesobjectsr   r   	TypeError)r@   itemrt   ru   rv   s        rB   __getitem__zGraph.__getitem__  s   T dE"jj$))TYY!qAyQY19||Q1I..qy..q11qy++A..qy--a00}}Q**q!,,||Aq)) 1ayD((tTl+))$// i rC   c                 :    | j                   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.
        r   )r;   __len__rF   s    rB   r   zGraph.__len__  s     ||##D#11rC   c                 $    | j                  d      S )z&Iterates over all triples in the storeNNNr   rF   s    rB   __iter__zGraph.__iter__%  s    ||.//rC   c                 2    | j                  |      D ]  } y y)z$Support for 'triple in graph' syntaxTFr   r   s     rB   __contains__zGraph.__contains__)  s     ll6* 	F	rC   c                 ,    t        | j                        S rE   )hashr1   rF   s    rB   __hash__zGraph.__hash__/  s    DOO$$rC   c                     |yt        |t              r3| j                  |j                  kD  | j                  |j                  k  z
  S y)N   r9   r&   r1   r@   others     rB   __cmp__zGraph.__cmp__2  sG    =u%OOe&6&66%"2"22  rC   c                 X    t        |t              xr | j                  |j                  k(  S rE   r   r   s     rB   __eq__zGraph.__eq__?  s#    %'ODOOu?O?O,OOrC   c                 d    |d u xs+ t        |t              xr | j                  |j                  k  S rE   r   r   s     rB   __lt__zGraph.__lt__B  s1     
ue$K5;K;K)K	
rC   c                     | |k  xs | |k(  S rE   rX   r   s     rB   __le__zGraph.__le__G      e|,tu},rC   c                 d    t        |t              xr | j                  |j                  kD  xs |d uS rE   r   r   s     rB   __gt__zGraph.__gt__J  s2    5%(OT__u?O?O-O 
	
rC   c                     | |kD  xs | |k(  S rE   rX   r   s     rB   __ge__zGraph.__ge__O  r   rC   c                 <      j                   fd|D                S )zKAdd all triples in Graph other to Graph.
        BNode IDs are not changed.c              3   2   K   | ]  \  }}}|||f  y wrE   rX   )r}   rt   ru   rv   r@   s       rB   r   z!Graph.__iadd__.<locals>.<genexpr>U  s     7gaA1aD/7s   )r   r   s   ` rB   __iadd__zGraph.__iadd__R  s     			777rC   c                 6    |D ]  }| j                  |        | S )zRSubtract all triples in Graph other from Graph.
        BNode IDs are not changed.)r   )r@   r   ri   s      rB   __isub__zGraph.__isub__X  s$      	 FKK	 rC   c                 f   	  t        |              }t        t	        | j                               t	        |j                               z         D ]  \  }}|j                  ||        | D ]  }|j                  |        |D ]  }|j                  |        |S # t        $ r t               }Y w xY w)z6Set-theoretic union
        BNode IDs are not changed.)rQ   r   r&   setlist
namespacesbindrr   )r@   r   retvalprefixurixys          rB   __add__zGraph.__add___  s    	T$Z\F !doo&7!84@P@P@R;S!ST 	%MVSKK$	% 	AJJqM	 	AJJqM	  	WF	s   B B0/B0c                     	  t        |              }|D ]  }|| v s|j                  |        |S # t        $ r t               }Y 4w xY w)z>Set-theoretic intersection.
        BNode IDs are not changed.rQ   r   r&   rr   r@   r   r   r   s       rB   __mul__zGraph.__mul__n  sV    	T$Z\F  	ADy

1	   	WF	   1 AAc                     	  t        |              }| D ]  }||vs|j                  |        |S # t        $ r t               }Y 4w xY w)z<Set-theoretic difference.
        BNode IDs are not changed.r   r   s       rB   __sub__zGraph.__sub__z  sV    	T$Z\F  	A~

1	   	WF	r   c                     | |z
  || z
  z   S )z5Set-theoretic XOR.
        BNode IDs are not changed.rX   r   s     rB   __xor__zGraph.__xor__  s     u..rC   c                     |\  }}}|J d       |J d       | j                  ||df       | j                  |||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   rr   )r@   ri   subject	predicateobject_s        rB   r   z	Graph.set  sm     )/%)W	LK	L !	LK	L!Wi./'9g./rC   returnc              #   N   K   | j                  d||f      D ]
  \  }}}|  yw)z;A generator of subjects with the given predicate and objectNr   )r@   r   objectrt   ru   rv   s         rB   r   zGraph.subjects  s0     ||T9f$=> 	GAq!G	   #%c              #   N   K   | j                  |d|f      D ]
  \  }}}|  yw)z;A generator of predicates with the given subject and objectNr   )r@   r   r   rt   ru   rv   s         rB   r   zGraph.predicates  s0     ||WdF$;< 	GAq!G	r   c              #   N   K   | j                  ||df      D ]
  \  }}}|  yw)z;A generator of objects with the given subject and predicateNr   )r@   r   r   rt   ru   rv   s         rB   r   zGraph.objects  s0     ||Wi$>? 	GAq!G	r   c              #   R   K   | j                  dd|f      D ]  \  }}}||f  yw)z?A generator of (subject, predicate) tuples for the given objectNr   )r@   r   rt   ru   rv   s        rB   r   zGraph.subject_predicates  s4     ||T4$89 	GAq!Q$J	   %'c              #   R   K   | j                  d|df      D ]  \  }}}||f  yw)z?A generator of (subject, object) tuples for the given predicateNr   )r@   r   rt   ru   rv   s        rB   r   zGraph.subject_objects  s4     ||T9d$;< 	GAq!Q$J	r   c              #   R   K   | j                  |ddf      D ]  \  }}}||f  yw)z?A generator of (predicate, object) tuples for the given subjectNr   )r@   r   rt   ru   rv   s        rB   r   zGraph.predicate_objects  s4     ||WdD$9: 	GAq!Q$J	r   c              #   ~   K   |\  }}}| j                   j                  |||f|       D ]  \  \  }}}}	|||f  y w)Nr   )r0   triples_choices)
r@   ri   r   r   r   r   rt   ru   rv   r   s
             rB   r   zGraph.triples_choices  sX     &,#G!ZZ77i)4 8 
 	MIQ1r Q'M	s   ;=Tc                    |}||||||y|| j                  ||      }|| j                  ||      }|| j                  ||      }	 t              }|du ru	 t        |       d|d|d|d}| j                  j                  |||fd      }	|	D ]$  \  \  }
}}}|d|
d|d|dt        |      d	z  }& t        j                  |      |S # t        $ r Y |S w xY w# t        $ r |}Y |S w xY w)	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

        Parameters:
        subject, predicate, object  -- exactly one 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   nextr0   r   r   r   UniquenessErrorStopIteration)r@   r   r   r   defaultanyr   valuesmsgr   rt   ru   rv   contextss                 rB   valuezGraph.value  sH   "  _!2FN!fn>\\'95F?]]9f5F__Wf5F	&\F e|L #Iv7 
 #jj00'9f1MtTG/6 +	Aq8 N	   %44S99  % )  	F* -	s%   C# A4C 	C C #C21C2c                     t        t        d             ||S | j                  |t        j                  j
                  |d      S )z{Query for the RDFS.label of the subject

        Return default if no label exists or any label if multiple exist.
        z@graph.label() is deprecated and will be removed in rdflib 6.0.0.Tr   r   )r   DeprecationWarningr   r   RDFSlabelr@   r   r   s      rB   r   zGraph.label  sD    
 	R	

 ?Nzz'9>>#7#7dzSSrC   c           
         t        t        d             |g }dk(  rd }n	fd}nd }|D ]I  }t        t        || j	                  ||                  }t        |      dk(  r7|D cg c]  }||f c}c S  |S c c}w )a	  
        Find the preferred label for subject.

        By default prefers skos:prefLabels over rdfs:labels. In case at least
        one prefLabel is found returns those, else returns labels. In case a
        language string (e.g., "en", "de" or even "" for no lang-tagged
        literals) is given, only such labels will be considered.

        Return a list of (labelProp, label) pairs, where labelProp is either
        skos:prefLabel or rdfs:label.

        >>> from rdflib import ConjunctiveGraph, URIRef, Literal, namespace
        >>> from pprint import pprint
        >>> g = ConjunctiveGraph()
        >>> u = URIRef("http://example.com/foo")
        >>> g.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.ConjunctiveGraph'>)>
        >>> g.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.ConjunctiveGraph'>)>
        >>> pprint(sorted(g.preferredLabel(u)))
        [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),
          rdflib.term.Literal('bar')),
         (rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),
          rdflib.term.Literal('foo'))]
        >>> g.add([u, namespace.SKOS.prefLabel, Literal("bla")]) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.ConjunctiveGraph'>)>
        >>> pprint(g.preferredLabel(u))
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla'))]
        >>> g.add([u, namespace.SKOS.prefLabel, Literal("blubb", lang="en")]) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.ConjunctiveGraph'>)>
        >>> sorted(g.preferredLabel(u)) #doctest: +NORMALIZE_WHITESPACE
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla')),
          (rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('blubb', lang='en'))]
        >>> g.preferredLabel(u, lang="") #doctest: +NORMALIZE_WHITESPACE
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla'))]
        >>> pprint(g.preferredLabel(u, lang="en"))
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('blubb', lang='en'))]
        zIgraph.preferredLabel() is deprecated and will be removed in rdflib 6.0.0. c                     | j                   d u S rE   languagel_s    rB   
langfilterz(Graph.preferredLabel.<locals>.langfilterM  s    ;;$..rC   c                 "    | j                   k(  S rE   r   )r   langs    rB   r   z(Graph.preferredLabel.<locals>.langfilterR  s    ;;$..rC   c                      y)NTrX   r   s    rB   r   z(Graph.preferredLabel.<locals>.langfilterW  s    rC   r   )r   r   r   filterr   len)	r@   r   r   r   labelPropertiesr   	labelProplabelsr   s	     `      rB   preferredLabelzGraph.preferredLabel  s    d 	[	

 ?G rz/
/
 ) 	:I&T\\'9-MNOF6{a289BB99	:  :s   +A>c                     t        t        d             ||S | j                  |t        j                  j
                  |d      S )z_Query for the RDFS.comment of the subject

        Return default if no comment exists
        zBgraph.comment() is deprecated and will be removed in rdflib 6.0.0.Tr   )r   r   r   r   r   commentr   s      rB   r  zGraph.commentb  sE    
 	T	

 ?Nzz'9>>#9#97PTzUUrC   c              #      K   t        |g      }|rj| j                  |t        j                        }|| | j                  |t        j                        }||v rt        d      |j                  |       |riyyw)zgGenerator over all items in the resource specified by list

        list is an RDF collection.
        Nz,List contains a recursive rdf:rest reference)r   r   r   firstrest
ValueErrorrr   )r@   r   chainr   s       rB   itemszGraph.itemsp  sl     
 TF::dCII.D
::dCHH-Du} !OPPIIdO s   A7A<:A<c              #      K   |i }n||v ryd||<    |||       D ]"  }| | j                  |||      D ]  }|  $ yw)a  
        Generates transitive closure of a user-defined
        function against the graph

        >>> from rdflib.collection import Collection
        >>> g=Graph()
        >>> a=BNode("foo")
        >>> b=BNode("bar")
        >>> c=BNode("baz")
        >>> g.add((a,RDF.first,RDF.type)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> g.add((a,RDF.rest,b)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> g.add((b,RDF.first,namespace.RDFS.label)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> g.add((b,RDF.rest,c)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> g.add((c,RDF.first,namespace.RDFS.comment)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> g.add((c,RDF.rest,RDF.nil)) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
        >>> 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)] # doctest: +NORMALIZE_WHITESPACE
        [rdflib.term.BNode('baz'),
         rdflib.term.BNode('bar'),
         rdflib.term.BNode('foo')]

        >>> [rt for rt in g.transitiveClosure(
        ...     reverseList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE
        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')]

        Nr   )transitiveClosure)r@   funcargseenrtrt_2s         rB   r  zGraph.transitiveClosure  sc     ^ <DD[S	sD/ 	BH..tR> 
	   ?Ac              #      K   |i }||v ryd||<   | | j                  ||      D ]  }| j                  |||      D ]  }|    yw)zTransitively generate objects for the ``predicate`` relationship

        Generated objects belong to the depth first transitive closure of the
        ``predicate`` relationship starting at ``subject``.
        Nr   )r   transitive_objects)r@   r   r   rememberr   rv   s         rB   r  zGraph.transitive_objects  sj      Hhll7I6 	F,,VYI 	   AA	c              #      K   |i }||v ryd||<   | | j                  ||      D ]  }| j                  |||      D ]  }|    yw)zTransitively generate subjects for the ``predicate`` relationship

        Generated subjects belong to the depth first transitive closure of the
        ``predicate`` relationship starting at ``object``.
        Nr   )r   transitive_subjects)r@   r   r   r  r   rt   s         rB   r  zGraph.transitive_subjects  sj      HX}}Y7 	G--i(K 	r  c                     t        t        d             |t        j                  t        j                  f| v rt	        | |      S y)ziCheck if subject is an rdf:Seq

        If yes, it returns a Seq class instance, None otherwise.
        z>graph.seq() is deprecated and will be removed in rdflib 6.0.0.N)r   r   r   rQ   r)   )r@   r   s     rB   seqz	Graph.seq  s@    
 	P	

 SXXsww'4/tW%%rC   c                 8    | j                   j                  |      S rE   )r2   qnamer@   r   s     rB   r  zGraph.qname  s    %%++C00rC   c                 :    | j                   j                  ||      S rE   )r2   compute_qnamer@   r   generates      rB   r   zGraph.compute_qname  s    %%33CBBrC   c                 @    | j                   j                  ||||      S )a6  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

        for example:  graph.bind("foaf", "http://xmlns.com/foaf/0.1/")

        )overridereplace)r2   r   )r@   r   r   r$  r%  s        rB   r   z
Graph.bind  s+     %%**I' + 
 	
rC   c              #   \   K   | j                   j                         D ]  \  }}||f  yw)z/Generator over all the prefix, namespace tuplesN)r2   r   )r@   r   r   s      rB   r   zGraph.namespaces  s4     !%!7!7!B!B!D 	$FI)##	$s   *,c                 :    | j                   j                  ||      S )z5Turn uri into an absolute URI if it's not one already)r2   
absolutizer@   r   defrags      rB   r(  zGraph.absolutize  s    %%00f==rC   destinationformatencodingc                      y rE   rX   r@   r+  r,  r3   r-  argss         rB   	serializezGraph.serialize  s     	rC   c                     y rE   rX   r/  s         rB   r1  zGraph.serialize  s     	rC   c                      y rE   rX   r/  s         rB   r1  zGraph.serialize       	rC   c                      y rE   rX   r/  s         rB   r1  zGraph.serialize&  r4  rC   c                      y rE   rX   r/  s         rB   r1  zGraph.serialize2  r4  rC   r0  c                    || j                   } t        j                  |t              |       }|gt	               }|5 |j
                  |f|dd| |j                         j                  d      S  |j
                  |f||d| |j                         S t        |d      r/t        t        t           |      } |j
                  |f||d| | S t        |t        j                        rt        |      }nt        t        |      }t!        |      \  }	}
}}}}|
dk7  rt#        d| d      t%        j&                         \  }}t)        j*                  |d      } |j
                  |f||d| |j-                          |	dk(  rt/        |      n|}t        t0        d	      rt1        j2                  ||       | S t1        j4                  ||       t)        j6                  |       | S )
a  Serialize the Graph to destination

        If destination is None serialize method returns the serialization as
        bytes or string.

        If encoding is None and destination is None, returns a string
        If encoding is set, and Destination is None, returns bytes

        Format defaults to turtle.

        Format support can be extended with plugins,
        but "xml", "n3", "turtle", "nt", "pretty-xml", "trix", "trig" and "nquads" are built in.
        utf-8)r3   r-  writer   zdestination z is not a local file referencewbfilemove)r3   r   r:   r   r#   r1  getvaluedecodehasattrr	   r   bytesr9   pathlibPurePathstrr$   r	  tempfilemkstemposfdopenrh   r%   shutilr<  copyr   )r@   r+  r,  r3   r-  r0  
serializerstreamlocationschemenetlocpathparams_queryfragmentfdnamedests                     rB   r1  zGraph.serialize=  s   . <99D3VZZ
3D9
YF$
$$VQ$QDQ(//88$
$$VR$RTR((;("U)[1F J  NdXNN* ' +w'7'78{+[1=Eh=O:FFD&&(| ";-/MN   '')HBYYr4(F J  NdXNNLLN)/6)9<%xDvv&D$'  D$'		$rC   c                 b    t        | j                  d ||      j                  |      |d       y )N)r,  r-  T)r;  flush)printr1  r>  )r@   r,  r-  outs       rB   rX  zGraph.printz  s-    NN4NBII(S	
rC   datac                 x   t        ||||||      }||j                  }d}|t        |d      rnt        |j                  dd      rWt        |j                  j                  t              r3t        j                  j                  |j                  j                        }|d}d} t        j                  |t                     }		  |	j                  || fi | 	 |j"                  r|j%                          | S # t        $ r}
|rt!        d|z        |
d}
~
ww xY w# |j"                  r|j%                          w w xY w)	a	  
        Parse an RDF source adding the resulting triples to the Graph.

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

        :Parameters:

          - `source`: An InputSource, file-like object, or string. In the case
            of a string the string is the location of the source.
          - `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.
          - `format`: Used if format can not be determined from source, e.g. file
            extension or Media Type. Defaults to text/turtle. Format support can
            be extended with plugins, but "xml", "n3" (use for turtle), "nt" &
            "trix" are built in.
          - `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).

        :Returns:

          - self, the graph instance.

        Examples:

        >>> 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 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

        sourcepublicIDrL  r;  rZ  r,  NFr;  rT  turtleTzCould 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;  r9   rT  rC  rdflibutilguess_formatr   r:   r   parseSyntaxErrorr"   
auto_closerh   )r@   r]  r^  r,  rL  r;  rZ  r0  could_not_guess_formatparserses              rB   re  zGraph.parse  s3   b %
 >((F!&>'FKK6v{{//511&++2B2BC~!)-&+FF+-	FLL..     	%!S  	    !s$   C7 7	D DDD D9c                 P    t        t        d             | j                  |||      S )Nzagraph.load() is deprecated, it will be removed in rdflib 6.0.0. Please use graph.parse() instead.)r   r   re  )r@   r]  r^  r,  s       rB   loadz
Graph.load  s,    4	
 zz&(F33rC   	processorresultuse_store_providedc                 f   |xs i }|xs t        | j                               }t        | j                  d      r?|r=	  | j                  j                  |||| j
                  xr dxs | j                  fi |S t        |t        j                        s2t        j                  t        t        |      t        j                        }t        |t        j                        s* t        j                  |t        j                        |       } | |j                  |||fi |      S # t        $ r Y w xY w)ap  
        Query this graph.

        A type of 'prepared queries' can be realised by providing
        initial variable bindings with initBindings

        Initial namespaces are used to resolve prefixes used in the query,
        if none are given, the namespaces from the graph's namespace manager
        are used.

        :returntype: rdflib.query.Result

        r   	__UNION__)dictr   r?  r0   r   r?   r1   NotImplementedErrorr9   Resultr   r:   r	   rC  	Processor)r@   query_objectrm  rn  initNsinitBindingsro  kwargss           rB   r   zGraph.query  s   0 $)r24 124::w',>	'tzz''  &&6;I$//	
   &%,,/ZZS& 15<<@F)U__5>

9eoo>tDIoioolL&SFSTT ' s   ;D$ $	D0/D0c                    |xs i }|xs t        | j                               }t        | j                  d      r?|r=	  | j                  j                  |||| j
                  xr dxs | j                  fi |S t        |t        j                        s* t        j                  |t        j                        |       } |j                  |||fi |S # t        $ r Y dw xY w)z.Update this graph with the given update query.updaterq  )rr  r   r?  r0   r{  r?   r1   rs  r9   r   UpdateProcessorr   r:   )r@   update_objectrm  rw  rx  ro  ry  s          rB   r{  zGraph.update0  s     $)r24 124::x(-?	(tzz((! &&6;I$//	
   )U%:%:;D

9e.C.CDTJIy|VNvNN ' s   ;C 	CCc                 <    d| j                   j                         z  S )%Return an n3 identifier for the Graphz[%s]r1   rT   rF   s    rB   rT   zGraph.n3N      **,,,rC   c                 >    t         | j                  | j                  ffS rE   )r&   r0   r1   rF   s    rB   
__reduce__zGraph.__reduce__R  s"    


 	
rC   c                    t        |       t        |      k7  ry| D ]1  \  }}}t        |t              rt        |t              r)|||f|vs1 y |D ]1  \  }}}t        |t              rt        |t              r)|||f| vs1 y y)z
        does a very basic check if these graphs are the same
        If no BNodes are involved, this is accurate.

        See rdflib.compare for a correct implementation of isomorphism checks
        FT)r   r9   r   )r@   r   rt   ru   rv   s        rB   
isomorphiczGraph.isomorphic[  s     t9E
" 	!GAq!a'
1e0D1ayE) 	!  	!GAq!a'
1e0D1ayD( 	!
 rC   c                    t        | j                               }g }|sy|t        j                  t	        |               g}|r|j                         }||vr|j                  |       | j                  |      D ]  }||vs||vs|j                  |        | j                  |      D ]  }||vs||vs|j                  |        |rt	        |      t	        |      k(  ryy)a  Check if the Graph is connected

        The Graph is considered undirectional.

        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. Return True if all nodes have been visited and
        False if it cannot continue and there are still unvisited nodes left.
        F)r   )r   T)	r   	all_nodesrandom	randranger   popappendr   r   )r@   r  
discoveredvisitingr   new_xs         rB   	connectedzGraph.connectedp  s     )*	
 f..s9~>?@A
"!!!$a0 +
*uH/DOOE*+ a0 +
*uH/DOOE*+  y>S_,rC   c                 v    t        | j                               }|j                  | j                                |S rE   )r   r   r{  r   )r@   ress     rB   r  zGraph.all_nodes  s)    $,,.!

4==?#
rC   c                     t        | |      S )a  Create a new ``Collection`` instance.

        Parameters:

        - ``identifier``: a URIRef or BNode instance.

        Example::

            >>> 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    r@   r1   s     rB   
collectionzGraph.collection  s    $ $
++rC   c                 P    t        |t              st        |      }t        | |      S )a  Create a new ``Resource`` instance.

        Parameters:

        - ``identifier``: a URIRef or BNode instance.

        Example::

            >>> 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

        )r9   r   r   r   r  s     rB   resourcezGraph.resource  s%    " *d+
+Jj))rC   c                 ^    | j                  d      D ]  }|j                   ||              y )Nr   )r   rr   )r@   targetr  ts       rB   _process_skolem_tupleszGraph._process_skolem_tuples  s+    01 	 AJJtAw	 rC   c                     fdfd}|
t               n|}| j                  ||       |S t        t              r| j                  |fd       |S )Nc                 z    |\  }}}|| k(  r|j                        }|| k(  r|j                        }|||fS N)	authoritybasepath)	skolemize)bnoder  rt   ru   rv   r  r  s        rB   do_skolemizez%Graph.skolemize.<locals>.do_skolemize  sK    IQ1EzKK)hKGEzKK)hKGa7NrC   c                     | \  }}}t        |t              r|j                        }t        |t              r|j                        }|||fS r  )r9   r   r  )r  rt   ru   rv   r  r  s       rB   do_skolemize2z&Graph.skolemize.<locals>.do_skolemize2  sQ    IQ1!U#KK)hKG!U#KK)hKGa7NrC   c                      |       S rE   rX   )r  r  r  s    rB   <lambda>z!Graph.skolemize.<locals>.<lambda>  s    ,ua:P rC   )r&   r  r9   r   )r@   	new_graphr  r  r  r  r   r  s     ```  @rB   r  zGraph.skolemize  s[    		 &-9=''>  u%''0PQrC   c                     d d }|
t               n|}| j                  ||       |S t        t              r| j                  |fd       |S )Nc                 l    |\  }}}|| k(  r|j                         }|| k(  r|j                         }|||fS rE   )de_skolemize)urirefr  rt   ru   rv   s        rB   do_de_skolemizez+Graph.de_skolemize.<locals>.do_de_skolemize  s>    IQ1F{NN$F{NN$a7NrC   c                     | \  }}}t        |t              r|j                         }t        |t              r|j                         }|||fS rE   )r9   r   r  )r  rt   ru   rv   s       rB   do_de_skolemize2z,Graph.de_skolemize.<locals>.do_de_skolemize2  sD    IQ1!U#NN$!U#NN$a7NrC   c                      |       S rE   rX   )r  r  r  s    rB   r  z$Graph.de_skolemize.<locals>.<lambda>  s    /&RS:T rC   )r&   r  r9   r   )r@   r  r  r  r   r  s     `  @rB   r  zGraph.de_skolemize  s\    		 &-9>''0@A  &''0TUrC   c                 >     t                fd |       S )a  Retrieves the Concise Bounded Description of a Resource from a Graph

        Concise Bounded Description (CBD) is defined in [1] 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.

        [1] https://www.w3.org/Submission/CBD/

        :param resource: a URIRef object, of the Resource for queried for
        :return: a Graph, subgraph of self

        c                 f   j                  | d d f      D ]=  \  }}}	j                  |||f       t        |      t        k(  s.|d d f	vs6 |       ? j                  d t        j
                  | f      D ]7  \  }}}j                  |d d f      D ]  \  }}}	j                  |||f        9 y rE   )r   rr   rQ   r   r   r   )
r   rt   ru   rv   s2p2o2
add_to_cbdr@   subgraphs
          rB   r  zGraph.cbd.<locals>.add_to_cbd  s    <<dD(9: "1aaAY'7e#QdOx,GqM	"  <<s{{C(@A /1a"&,,4"? /JBBLL"b".//rC   )r&   )r@   r  r  r  s   ` @@rB   cbdz	Graph.cbd  s     : 7	/$ 	8rC   )r   NNNFNNrE   )r   T)TFr   )...)....)Nr_  NN)r_  r8  NNNNNNN)Nxml)sparqlr  NNT)r  NNTNNNN)mrU   
__module____qualname____doc__r   r   rC  r   r   r   r7   _Graph__get_storepropertyr0   _Graph__get_identifierr1   rK   rN   r2   rR   rV   rY   r\   r`   rb   rd   rh   r   rr   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   r   r   SKOS	prefLabelr   r  r  r  r  r  r  r  r  r   r   r   r(  r
   r@  r1  rA  rB  r   rX  	bytearrayre  rl  r   ru  r   rt  boolr{  rT   r  r  r  r  r  r  r  r  r  r  __classcell__rA   s   @rB   r&   r&   4  s   ( $-158<"#UCZ # U49-.# $$45	#
 sm#0 [!E! *+J(
& !,L.

8Y%dD 01 
(5tT3)>#?@ 
HTNE$d2B,CXd^ST FP20%P

-

-

/
 FG"x~ 
x~ 
x~ 



 ciidPT9vT" "119>>3G3GHQfV7r  1C
$
>
 ),4<SMMP	    !			 	 sm		 	 
	 	   !  sm	
  
   !"%3 0 0"U);<  sm	
 3- 
   JM!"%eC)9)92e9$DEF  sm	
 3- 
uc7"	#  JN""&;eC)9)92e9$DEF; ; sm	;
 3-; ; 
uc7"	#;z
  $7;v 	v uS%234vp4 2:19#',U eoo-.,U c4--.	,U !,U 
,Ub O<-
*#J
,(** 443rC   r&   c                       e Zd ZdZ	 	 	 d#deeef   deeeef      dee   f fdZ	d Z
e	 d$d	eeeeeee   f   eeeef   f   ded
eeeeee   f   fd       Ze	 d$d	dded
edddee   f   fd       Z	 d$d	eeeeeeee   f   eeeef   f      ded
eee   ee   ee   ee   f   fdZd Zd	eeeeeee   f   eeeef   f   d
d fdZedeeeef   d
efd       Zed%d       Zdeeeeef      d
ee   fdZdeeeeeef      fdZd Zd&dZd&dZd&dZd Zd&dZ	 	 d'deeeef      dedee   d
efdZd Zd&d Z	 	 	 	 	 	 d(d!Zd" Z  xZ!S ))r'   a  A ConjunctiveGraph is an (unnamed) aggregation of all the named
    graphs in a store.

    It has a ``default`` graph, whose name is associated with the
    graph throughout its life. :meth:`__init__` 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.
    r   Nr0   r1   default_graph_basec                     t         t        |   ||       | j                  j                  sJ d       d| _        d| _        t        | j                  |xs
 t               |      | _        y )N)r1   z9ConjunctiveGraph must be backed by a context aware store.Tr0   r1   r3   )	r6   r'   r7   r0   r=   r?   r&   r   default_context)r@   r0   r1   r  rA   s       rB   r7   zConjunctiveGraph.__init__?  si     	.u.Lzz'' 	
J	
' "!$**)>uwEW 
rC   c                 L    d}|| j                   j                  j                  z  S )NzK[a rdflib:ConjunctiveGraph;rdflib:storage [a rdflib:Store;rdfs:label '%s']]r0   rA   rU   r@   patterns     rB   rV   zConjunctiveGraph.__str__O  s)    0 	 --6666rC   triple_or_quadr   c                      y rE   rX   r@   r  r   s      rB   _spoczConjunctiveGraph._spocV  s     	rC   c                      y rE   rX   r  s      rB   r  zConjunctiveGraph._spoc`  s     	rC   c                     |ddd|r| j                   fS dfS t        |      dk(  r|r| j                   nd}|\  }}}n&t        |      dk(  r|\  }}}}| j                  |      }fS )z_
        helper method for having methods that support
        either triples or quads
        N      )r  r   _graph)r@   r  r   r~   rt   ru   rv   s          rB   r  zConjunctiveGraph._spoch  s     !$gd&:&:PP4PP~!#(/$$TA&IQ1 A%)LQ1aAA!QzrC   c                 h    | j                  |      \  }}}}| j                  |||f|      D ]  } y y)z)Support for 'triple/quad in graph' syntaxr   TF)r  r   )r@   r  rt   ru   rv   r~   r  s          rB   r   zConjunctiveGraph.__contains__}  s@    ZZ/
1aq!Qi3 	A	rC   c                     | j                  |d      \  }}}}t        |||       | j                  j                  |||f|d       | S )zu
        Add a triple or quad to the store.

        if a triple is given it is added to the default context
        Tr   F)r   rq   )r  r{   r0   rr   r@   r  rt   ru   rv   r~   s         rB   rr   zConjunctiveGraph.add  sK     ZZZ=
1aAq!

1ay!E:rC   r~   c                      y rE   rX   r@   r~   s     rB   r  zConjunctiveGraph._graph      rC   c                      y rE   rX   r  s     rB   r  zConjunctiveGraph._graph  r  rC   c                 N    |y t        |t              s| j                  |      S |S rE   )r9   r&   get_contextr  s     rB   r  zConjunctiveGraph._graph  s*    9!U###A&&HrC   rw   c                 P      j                   j                   fd|D                S )z&Add a sequence of triples with contextc              3   n   K   | ],  \  }}}}t        |||      s|||j                  |      f . y wrE   )r{   r  r|   s        rB   r   z(ConjunctiveGraph.addN.<locals>.<genexpr>  s<      
*4!Q1QPQSTAUQ1dkk!n%
s   55r0   r   r   s   ` rB   r   zConjunctiveGraph.addN  s)     	

 
8=
 	
 rC   c                 r    | j                  |      \  }}}}| j                  j                  |||f|       | S )z
        Removes 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  r0   r   r  s         rB   r   zConjunctiveGraph.remove  s<     ZZ/
1a

1a)Q/rC   c              #     K   | j                  |      \  }}}}| j                  |xs |      }| j                  r|| j                  k(  rd}n|| j                  }t	        |t
              r'|| }|j                  |||      D ]  \  }}|||f  y| j                  j                  |||f|      D ]  \  \  }}}}|||f  yw)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  r  r?   r  r9   r   r   r0   r   )r@   r  r   rt   ru   rv   r~   r   s           rB   r   zConjunctiveGraph.triples  s      ZZ/
1a++gl+$.....aw1- 1Ag "&!3!3Q1Iw!3!O 	Aq2Ags   CCc              #      K   | j                  |      \  }}}}| j                  j                  |||f|      D ]  \  \  }}}}|D ]
  }||||f   yw)z:Iterate over all the quads in the entire conjunctive graphr   N)r  r0   r   )r@   r  rt   ru   rv   r~   r   ctxs           rB   rw   zConjunctiveGraph.quads  sn      ZZ/
1a!ZZ//Aq	1/E 	#MIQ1r #Asl"#	#s   AAc              #      K   |\  }}}|| j                   s| j                  }n| j                  |      }| j                  j	                  |||f|      D ]  \  \  }}}}	|||f  yw)z<Iterate over all the triples in the entire conjunctive graphNr   )r?   r  r  r0   r   )
r@   ri   r   rt   ru   rv   s1p1o1r   s
             rB   r   z ConjunctiveGraph.triples_choices  sx     1a?%%..kk'*G $

 : :Aq!9g : V 	LRR"b"*	s   A'A)c                 6    | j                   j                         S )z1Number of triples in the entire conjunctive graph)r0   r   rF   s    rB   r   zConjunctiveGraph.__len__  s    zz!!##rC   c              #      K   | j                   j                  |      D ]*  }t        |t              r| | j	                  |       , yw)z|Iterate over all contexts in the graph

        If triple is specified, iterate over all contexts the triple is in.
        N)r0   r   r9   r&   r  )r@   ri   r   s      rB   r   zConjunctiveGraph.contexts  sH     
 zz**62 	0G'5) &&w//	0s   A
Arq   r3   c                 4    t        | j                  || |      S )zgReturn a context graph for the given identifier

        identifier must be a URIRef or BNode.
        )r0   r1   r2   r3   )r&   r0   )r@   r1   rq   r3   s       rB   r  zConjunctiveGraph.get_context  s     **tRV
 	
rC   c                 <    | j                   j                  d|       y)z(Removes the given context from the graphr   N)r0   r   )r@   r   s     rB   remove_contextzConjunctiveGraph.remove_context  s    

,g6rC   c                 N    |j                  dd      d   }|d}t        ||      S )zURI#context#r   r   z#context)r3   )splitr   )r@   r   
context_ids      rB   r  zConjunctiveGraph.context_id  s/    iiQ"#Jjs++rC   c                 
   t        ||||||      }|xr |xs |j                         }t        |t              st	        |      }t        | j                  |      }	|	j                  d        |	j                  |f||d| |	S )a>  
        Parse source adding the resulting triples to its own context
        (sub graph of this graph).

        See :meth:`rdflib.graph.Graph.parse` for documentation on arguments.

        :Returns:

        The graph into which the source was parsed. In the case of n3
        it returns the root context.
        r\  r0   r1   r   )r^  r,  )	r   getPublicIdr9   r   r   r&   r0   r   re  )
r@   r]  r^  r,  rL  r;  rZ  r0  g_idr   s
             rB   re  zConjunctiveGraph.parse  s    , %
 $H<(:(:(<$%$<DdjjT:)*fGxG$GrC   c                 >    t         | j                  | j                  ffS rE   )r'   r0   r1   rF   s    rB   r  zConjunctiveGraph.__reduce__?  s    $**doo!>>>rC   )r   NNr  )r~   Nr   NrE   )FNr  )"rU   r  r  r  r   r   rC  r   r   r7   rV   r
   r   r   r  r&   r  r   rr   r  r   r   r   r   rw   r   r   r   r  r  r  re  r  r  r  s   @rB   r'   r'   1  s    $-15,0	
UCZ 
 U49-.
 %SM	
 7  $dHSM12E$d:J4KK

  
tT4%0	1     
tT4%0	1	   %dD(3-78%dD@P:QQR

  
x~x~x~xN	O*%dD$.M(NPUVZ\`bfVfPg(g"h m  eT3./ E    udC'7!89 huo (5tT3)>#?@ :#
$0" "	
U49-.
 
 sm	

 

7, 'R?rC   r'   zurn:x-rdflib:defaultc                        e Zd ZdZd fd	Zd Zd Zd Zd ZddZ		 	 	 	 	 	 dd	Z
d
 Zd Zd fd	ZeZ fdZdeeddf   fdZ xZS )r+   a?  
    RDF 1.1 Dataset. 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
    operate with graphs
    - graphs cannot be identified with blank nodes
    - added a method to directly add a single quad

    Examples of usage:

    >>> # 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)  # doctest:
    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
    http://rdlib.net/.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)

    .. versionadded:: 4.0
    Nc                     t         t        |   |d        | j                  j                  st        d      t        | j                  t        |      | _        || _	        y )Nr  z.DataSet must be backed by a graph-aware store!r  )
r6   r+   r7   r0   graph_aware	Exceptionr&   DATASET_DEFAULT_GRAPH_IDr  r?   )r@   r0   r?   r  rA   s       rB   r7   zDataset.__init__  sT    gt%Ed%Czz%%LMM$**/# 
 +rC   c                 L    d}|| j                   j                  j                  z  S )NzB[a rdflib:Dataset;rdflib:storage [a rdflib:Store;rdfs:label '%s']]r  r  s     rB   rV   zDataset.__str__  s'    S 	 --6666rC   c                 H    t        |       | j                  | j                  ffS rE   )rQ   r0   r?   rF   s    rB   r  zDataset.__reduce__  s     T
TZZ););<==rC   c                 ^    | j                   | j                  | j                  | j                  fS rE   r0   r1   r  r?   rF   s    rB   __getstate__zDataset.__getstate__  s%    zz4??D,@,@$BTBTTTrC   c                 :    |\  | _         | _        | _        | _        y rE   r  )r@   states     rB   __setstate__zDataset.__setstate__  s    PUM
DOT%94;MrC   c                     |5ddl m} | j                  dd|z   d       t               j	                         }| j                  |      }||_        | j                  j                  |       |S )Nr   )rdflib_skolem_genidgenidzhttp://rdflib.netF)r$  )	rdflib.termr  r   r   r  r  r3   r0   	add_graph)r@   r1   r3   r  gs        rB   graphzDataset.graph  sh    7II,/BBU   **,JKK
#

QrC   c           	      `    t        j                  | ||||||fi |}| j                  |       |S rE   )r'   re  r  )	r@   r]  r^  r,  rL  r;  rZ  r0  r~   s	            rB   re  zDataset.parse  s=     ""&(FHdD
DH
 	

1rC   c                 $    | j                  |      S )zalias of graph for consistency)r  r@   r  s     rB   r  zDataset.add_graph  s    zz!}rC   c                     t        |t              s| j                  |      }| j                  j	                  |       ||| j
                  k(  r%| j                  j                  | j
                         | S rE   )r9   r&   r  r0   remove_graphr  r  r  s     rB   r  zDataset.remove_graph   s_    !U#  #A

"9T111 JJ  !5!56rC   c              #      K   d}t         t        |   |      D ]  }||j                  t        k(  z  }|  |s| j                  t               y y wr5   )r6   r+   r   r1   r  r  )r@   ri   r   r~   rA   s       rB   r   zDataset.contexts  sZ     w.v6 	Aq||'???GG	 **566 s   AAc              #      K   t         t        |   |      D ];  \  }}}}|j                  | j                  k(  r	|||d f *||||j                  f = y wrE   )r6   r+   rw   r1   r  )r@   quadrt   ru   rv   r~   rA   s         rB   rw   zDataset.quads  s]     4T: 	,JAq!Q||t333Atm#Aq||++		,s   AAr   c                 $    | j                  d      S )z$Iterates over all quads in the storer  )rw   rF   s    rB   r   zDataset.__iter__  s    zz233rC   )r   FNr  r  rE   )rU   r  r  r  r7   rV   r  r  r  r  re  r  r  r   graphsrw   r   DatasetQuadr   r  r  s   @rB   r+   r+   F  sx    xGt+7>UV"  	7 F,4)Kt$;< 4rC   r+   c                   j     e Zd ZdZ fdZdeeeef   fdZdeeeeef   dd fdZ	d Z
d	 Zd
 Z xZS )r(   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.
    c                 .    t         t        |   ||       y rE   )r6   r(   r7   )r@   r0   r1   rA   s      rB   r7   zQuotedGraph.__init__)  s    k4)%<rC   ri   c                     |\  }}}t        |t              sJ d|d       t        |t              sJ d|d       t        |t              sJ d|d       | j                  j                  |||f| d       | S )rk   rl   rm   rn   ro   Trp   )r9   r   r0   rr   rs   s        rB   rr   zQuotedGraph.add,  sv    1a!T"N1$NN"!T"PQ$PP"!T"M!$MM"

1ay$t4rC   rw   r   c                 P      j                   j                   fd|D                S )ry   c              3      K   | ]D  \  }}}}t        |t              r-|j                  j                  u rt        |||      r||||f F y wrE   )r9   r(   r1   r{   r|   s        rB   r   z#QuotedGraph.addN.<locals>.<genexpr>9  sO      
1a![)/Aq!$	 1aL
r   r  r   s   ` rB   r   zQuotedGraph.addN6  s)     	

 
#
 	
 rC   c                 <    d| j                   j                         z  S )r  z{%s}r  rF   s    rB   rT   zQuotedGraph.n3B  r  rC   c                     | j                   j                         }| j                  j                  j                  }d}|||fz  S )NzK{this rdflib.identifier %s;rdflib:storage [a rdflib:Store;rdfs:label '%s']})r1   rT   r0   rA   rU   )r@   r1   r   r  s       rB   rV   zQuotedGraph.__str__F  sE    __'')


$$--0 	 *e,,,rC   c                 >    t         | j                  | j                  ffS rE   )r(   r0   r1   rF   s    rB   r  zQuotedGraph.__reduce__O  s    TZZ999rC   )rU   r  r  r  r7   r   r   rr   r   r   rT   rV   r  r  r  s   @rB   r(   r(   !  sU    =%dD 01 
%dD# 56 
= 
--:rC   r(      c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)r)   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.
    c                 .   t               x}| _        t        t        t              dz         }|j                  |      D ]E  \  }}|j                  |      st        |j                  |d            }|j                  ||f       G |j                          y)a  Parameters:

        - 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   N)r   _listr   rC  r   r   
startswithintr%  r  sort)r@   r  r   r.  LI_INDEXru   rv   is           rB   r7   zSeq.__init__c  s~     "V#
#c(S.)--g6 	%FQ||H%		(B/0aV$	% 	

rC   c                     | S rE   rX   rF   s    rB   rY   zSeq.toPythonz  rZ   rC   c              #   <   K   | j                   D ]	  \  }}|  yw)z#Generator over the items in the SeqN)r.  )r@   r-  r   s      rB   r   zSeq.__iter__}  s"     zz 	GAtJ	s   c                 ,    t        | j                        S )zLength of the Seq)r   r.  rF   s    rB   r   zSeq.__len__  s    4::rC   c                 B    | j                   j                  |      \  }}|S )z Item given by index from the Seq)r.  r   )r@   indexr   s      rB   r   zSeq.__getitem__  s    jj,,U3trC   N)	rU   r  r  r  r7   rY   r   r   r   rX   rC   rB   r)   r)   Z  s     .
rC   r)   c                       e Zd Zd Zd Zy)r*   c                      y rE   rX   rF   s    rB   r7   zModificationException.__init__      rC   c                      	 y)NzZModifications and transactional operations not allowed on ReadOnlyGraphAggregate instancesrX   rF   s    rB   rV   zModificationException.__str__  s    /	
rC   NrU   r  r  r7   rV   rX   rC   rB   r*   r*     s    
rC   r*   c                       e Zd Zd Zd Zy)r,   c                      y rE   rX   rF   s    rB   r7   z&UnSupportedAggregateOperation.__init__  r;  rC   c                      y)NzCThis operation is not supported by ReadOnlyGraphAggregate instancesrX   rF   s    rB   rV   z%UnSupportedAggregateOperation.__str__  s    WrC   Nr=  rX   rC   rB   r,   r,     s    XrC   r,   c                        e Zd ZdZd fd	Zd Zd Zd Zd ZddZ	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZd Zd dZd dZd Zd!dZd"dZd Zd Z xZS )#r-   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.
    c                     |0t         t        |   |       t        j                  | |       d | _        t        |t              r#|r!|D cg c]  }t        |t              s| c}sJ d       || _        y c c}w )Nz*graphs argument must be a list of Graphs!!)r6   r-   r7   r&   *_ReadOnlyGraphAggregate__namespace_managerr9   r   r   )r@   r   r0   r  rA   s       rB   r7   zReadOnlyGraphAggregate.__init__  sw    ($8?NN4''+D$ vt$";qjE&:;	8 8		8<  <s   
A6 A6c                 2    dt        | j                        z  S )Nz#<ReadOnlyGraphAggregate: %s graphs>)r   r   rF   s    rB   rR   zReadOnlyGraphAggregate.__repr__  s    4s4;;7GGGrC   c                     t               rE   r*   r]   s     rB   r\   zReadOnlyGraphAggregate.destroy      #%%rC   c                     t               rE   rF  rF   s    rB   r`   zReadOnlyGraphAggregate.commit  rG  rC   c                     t               rE   rF  rF   s    rB   rb   zReadOnlyGraphAggregate.rollback  rG  rC   c                 L    | j                   D ]  }|j                  | ||        y rE   )r   rd   )r@   r^   re   r  s       rB   rd   zReadOnlyGraphAggregate.open  s%    [[ 	4EJJt]F3	4rC   c                 F    | j                   D ]  }|j                           y rE   )r   rh   )r@   r  s     rB   rh   zReadOnlyGraphAggregate.close  s    [[ 	EKKM	rC   c                     t               rE   rF  r   s     rB   rr   zReadOnlyGraphAggregate.add  rG  rC   c                     t               rE   rF  r   s     rB   r   zReadOnlyGraphAggregate.addN  rG  rC   c                     t               rE   rF  r   s     rB   r   zReadOnlyGraphAggregate.remove  rG  rC   c              #      K   |\  }}}| j                   D ]Y  }t        |t              r#|j                  | ||      D ]  \  }}|||f  6|j	                  |||f      D ]  \  }}}|||f  [ y wrE   )r   r9   r   r   r   	r@   ri   rt   ru   rv   r  r  r  r  s	            rB   r   zReadOnlyGraphAggregate.triples  s     1a[[ 	%E!T"FF4A. "DAqQ'M" #(--Aq	": %JBBb"*$%	%s   A0A2c                     d }t        |      dk(  r|d   }| j                  D ]'  }||j                  |j                  k(  s|d d |v s' y y)Nr  r  TF)r   r   r1   )r@   r  r   r  s       rB   r   z#ReadOnlyGraphAggregate.__contains__  s`    ~!#$Q'G[[ 	 E%"2"2g6H6H"H!"1%.	  rC   c              #      K   |\  }}}| j                   D ]'  }|j                  |||f      D ]  \  }}}||||f  ) yw)z8Iterate over all the quads in the entire aggregate graphN)r   r   rP  s	            rB   rw   zReadOnlyGraphAggregate.quads  sW     1a[[ 	(E#mmQ1I6 (
B"b%''(	(s   >A c                 :    t        d | j                  D              S )Nc              3   2   K   | ]  }t        |        y wrE   )r   )r}   r  s     rB   r   z1ReadOnlyGraphAggregate.__len__.<locals>.<genexpr>  s     /a3q6/s   )sumr   rF   s    rB   r   zReadOnlyGraphAggregate.__len__  s    /4;;///rC   c                     t               rE   r,   rF   s    rB   r   zReadOnlyGraphAggregate.__hash__      +--rC   c                     |yt        |t              ryt        |t              r3| j                  |j                  kD  | j                  |j                  k  z
  S y)Nr   )r9   r&   r-   r   r   s     rB   r   zReadOnlyGraphAggregate.__cmp__  sJ    =u%56KK%,,.4;;3MNNrC   c                     t               rE   rF  r   s     rB   r   zReadOnlyGraphAggregate.__iadd__  rG  rC   c                     t               rE   rF  r   s     rB   r   zReadOnlyGraphAggregate.__isub__ 	  rG  rC   c              #      K   |\  }}}| j                   D ](  }|j                  |||f      }|D ]  \  }}	}
||	|
f  * y wrE   )r   r   )r@   ri   r   r   r   r   r  choicesrt   ru   rv   s              rB   r   z&ReadOnlyGraphAggregate.triples_choices	  s\     &,#G[[ 	E++Wi,IJG$ 	AqAg	r  c                 |    t        | d      r'| j                  r| j                  j                  |      S t               Nr2   )r?  r2   r  r,   r  s     rB   r  zReadOnlyGraphAggregate.qname	  s5    4,-$2H2H))//44+--rC   c                 ~    t        | d      r(| j                  r| j                  j                  ||      S t               r_  )r?  r2   r   r,   r!  s      rB   r   z$ReadOnlyGraphAggregate.compute_qname	  s7    4,-$2H2H))77XFF+--rC   c                     t               rE   rW  )r@   r   r   r$  s       rB   r   zReadOnlyGraphAggregate.bind	  rX  rC   c              #      K   t        | d      r)| j                  j                         D ]  \  }}||f  y | j                  D ]   }|j                         D ]  \  }}||f  " y wr_  )r?  r2   r   r   )r@   r   r   r  s       rB   r   z!ReadOnlyGraphAggregate.namespaces	  s|     4,-%)%;%;%F%F%H (!	i''(  ,).)9)9); ,%FI )++,,s   A&A(c                     t               rE   rW  r)  s      rB   r(  z!ReadOnlyGraphAggregate.absolutize"	  rX  rC   c                     t               rE   rF  )r@   r]  r^  r,  r0  s        rB   re  zReadOnlyGraphAggregate.parse%	  rG  rC   c                     t               rE   rW  rF   s    rB   rT   zReadOnlyGraphAggregate.n3(	  rX  rC   c                     t               rE   rW  rF   s    rB   r  z!ReadOnlyGraphAggregate.__reduce__+	  rX  rC   r  r  rE   r  r  r  ) rU   r  r  r  r7   rR   r\   r`   rb   rd   rh   rr   r   r   r   r   rw   r   r   r   r   r   r   r  r   r   r   r(  re  rT   r  r  r  s   @rB   r-   r-     s    H&&&4
&&&%(0.&&
.
.
.,.&..rC   r-   c                  H    | D ]  }t        |t              rJ d|d        y)NzTerm rm   T)r9   r   )termsr  s     rB   r{   r{   /	  s.     L!T"K$KK"LrC   c                       e Zd ZdZddededefdZd Zde	e
eeef   e
eeeef   f   dd fd	Zd
ee
eeeef      fdZd Zd Zy)r.   a)  
    Wrapper around graph that turns batches of calls to Graph's add
    (and optionally, addN) into calls to batched calls to addN`.

    :Parameters:

      - 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

    graph: The wrapped graph
    count: The number of triples buffered since initialization or the last call to reset
    batch: The current buffer of triples

    r  
batch_size
batch_addnc                     |r|dk  rt        d      || _        |f| _        || _        || _        | j                          y )N   z$batch_size must be a positive number)r	  r  _BatchAddGraph__graph_tuple_BatchAddGraph__batch_size_BatchAddGraph__batch_addnreset)r@   r  rj  rk  s       rB   r7   zBatchAddGraph.__init__H	  sA    Z!^CDD
#X&&

rC   c                 "    g | _         d| _        | S )zQ
        Manually clear the buffered triples and reset the count to zero
        r   )batchcountrF   s    rB   rq  zBatchAddGraph.resetQ	  s     

rC   r  r   c                 r   t        | j                        | j                  k\  r,| j                  j	                  | j                         g | _        | xj
                  dz  c_        t        |      dk(  r*| j                  j                  || j                  z          | S | j                  j                  |       | S )zV
        Add a triple to the buffer

        :param triple: The triple to add
        r   r  )r   rs  ro  r  r   rt  r  rn  )r@   r  s     rB   rr   zBatchAddGraph.addY	  s     tzz?d///JJOODJJ'DJ

a
~!#JJnt/A/AAB  JJn-rC   rw   c                     | j                   r|D ]  }| j                  |        | S | j                  j                  |       | S rE   )rp  rr   r  r   )r@   rw   qs      rB   r   zBatchAddGraph.addNl	  sC       JJOOE"rC   c                 &    | j                          | S rE   )rq  rF   s    rB   	__enter__zBatchAddGraph.__enter__t	  s    

rC   c                 Z    |d   &| j                   j                  | j                         y y Nr   )r  r   rs  )r@   excs     rB   __exit__zBatchAddGraph.__exit__x	  s$    q6>JJOODJJ' rC   N)i  F)rU   r  r  r  r&   r0  r  r7   rq  r   r   r   r   rr   r   r   ry  r}  rX   rC   rB   r.   r.   5	  s    $e   eD$$45uT4s=R7SST 
&(5tT3)>#?@ (rC   r.   c                  ,    dd l } | j                          y r{  )doctesttestmod)r  s    rB   testr  }	  s    OOrC   __main__)Otypingr   r   r   r   r   r   r	   r
   r   r   loggingwarningsr   r  rdflib.namespacer   r   rb  r   r   r   r   r  r   r   r   r   r   rdflib.pathsr   rdflib.storer   rdflib.serializerr   rdflib.parserr   r   r   rdflib.resourcer   rdflib.collectionr!   rdflib.utilrdflib.exceptionsr"   rF  rH  rD  rA  ior#   urllib.parser$   urllib.requestr%   	getLoggerrU   loggerContextNoder!  r  __all__r&   r'   r  r+   r(   term	_ORDERINGr   r)   r  r*   r,   r-   r{   r.   r  rX   rC   rB   <module>r     s}        + 7 7  ; ;   ( 5 - $ (  ) 	     ! 'w y			8	$ E6M"D&$(==>tn
zD zz'O?u O?d ""89 X4 X4v/:% /:l &(  k "/& /d
I 
XI XM.- M.`E(F E(P zF rC   