3
d                @   s"  d dl mZ d dl mZ d dl mZ d dlmZ es8td dlmZ esLtdZ	d dl
Z
e
jeZd dlZd dlmZmZmZ d d	lmZmZmZ d d
lmZmZmZ d dlmZ d dlZd dlmZ d dlmZ d dlmZ d dl m!Z! d dl m"Z" d dlm#Z# d dl$m%Z% d dl&m'Z' d dl(Z(d dl)Z)d dl*Z*d dl+m,Z, d dl+m-Z- d dl.m/Z/ ddddddddgZ0G dd deZ1G d d de1Z2ed!Z3G d"d de2Z4G d#d de1Z5d$ej6j7e5< G d%d de8Z9G d&d de:Z;G d'd de:Z<G d(d de2Z=d)d* Z>d+d, Z?ed-kre?  dS ).    )absolute_import)division)print_function)Literal)	NamespaceaH  
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 (IOMemory) and default identifier
(a BNode):

    >>> g = Graph()
    >>> g.store.__class__
    <class 'rdflib.plugins.memory.IOMemory'>
    >>> g.identifier.__class__
    <class 'rdflib.term.BNode'>

Instantiating Graphs with a IOMemory store and an identifier -
<http://rdflib.net>:

    >>> g = Graph('IOMemory', 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 'IOMemory']."

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 'IOMemory']]."

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))
    >>> g.add((statementId, RDF.subject,
    ...     URIRef("http://rdflib.net/store/ConjunctiveGraph")))
    >>> g.add((statementId, RDF.predicate, RDFS.label))
    >>> g.add((statementId, RDF.object, Literal("Conjunctive 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))
    >>> 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, RDFS.label, Literal("foo")])
    >>> g1.add([u, RDFS.label, Literal("bar")])
    >>> g2.add([u, RDFS.label, Literal("foo")])
    >>> g2.add([u, RDFS.label, Literal("bing")])
    >>> 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("IOMemory", Store)()
    >>> g1 = Graph(store)
    >>> g2 = Graph(store)
    >>> g3 = Graph(store)
    >>> stmt1 = BNode()
    >>> stmt2 = BNode()
    >>> stmt3 = BNode()
    >>> g1.add((stmt1, RDF.type, RDF.Statement))
    >>> g1.add((stmt1, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g1.add((stmt1, RDF.predicate, RDFS.label))
    >>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph')))
    >>> g2.add((stmt2, RDF.type, RDF.Statement))
    >>> g2.add((stmt2, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g2.add((stmt2, RDF.predicate, RDF.type))
    >>> g2.add((stmt2, RDF.object, RDFS.Class))
    >>> g3.add((stmt3, RDF.type, RDF.Statement))
    >>> g3.add((stmt3, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g3.add((stmt3, RDF.predicate, RDFS.comment))
    >>> g3.add((stmt3, RDF.object, Literal(
    ...     'The top-level aggregate graph - The sum ' +
    ...     'of all named graphs within a Store')))
    >>> 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')

N)RDFRDFSSKOS)plugin
exceptionsquery)NodeURIRefGenid)BNode)Path)Store)
Serializer)Parser)create_input_source)NamespaceManager)Resource)
Collection)BytesIO)b)urlparseGraphConjunctiveGraphQuotedGraphSeqModificationExceptionDatasetUnSupportedAggregateOperationReadOnlyGraphAggregatec                   s  e Zd ZdZd fdd	Zdd ZeeZdd	 ZeeZ	d
d Z
dd Zee
eddZdd Zdd Zdd Zdd Zdd Zdd ZdddZddd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Z d9d: Z!d;d< Z"d=d> Z#d?d@ Z$dAdB Z%dCdD Z&dEdF Z'dGdH Z(dIdJ Z)e&Z*e'Z+dKdL Z,ddMdNZ-ddOdPZ.ddQdRZ/ddSdTZ0ddUdVZ1ddWdXZ2ddYdZZ3de4j5ddd[fd\d]Z5dd_d`Z6dde7j8e9j6ffdadbZ:ddcddZ;dedf Z<ddgdhZ=ddidjZ>ddkdlZ?dmdn Z@dodp ZAddqdrZBddsdtZCdudv ZDddxdyZEdd{d|ZFdd}d~ZGdddZHdddZIdddZJdd ZKdd ZLdd ZMdd ZNdd ZOdd ZPdd ZQdd ZRdddZSdddZT  ZUS )r   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/
    defaultNc                sz   t t| j  || _|pt | _t| jts8t| j| _t|t	sXt
j|t	  | _}n|| _|| _d| _d| _d| _d S )NF)superr   __init__baser   _Graph__identifier
isinstancer   r   r   r
   get_Graph__store_Graph__namespace_managercontext_awareZformula_awaredefault_union)selfstore
identifiernamespace_managerr'   )	__class__ ./tmp/pip-build-7vycvbft/rdflib/rdflib/graph.pyr&   (  s    
zGraph.__init__c             C   s   | j S )N)r+   )r/   r4   r4   r5   Z__get_store:  s    zGraph.__get_storec             C   s   | j S )N)r(   )r/   r4   r4   r5   Z__get_identifier?  s    zGraph.__get_identifierc             C   s   | j d krt| | _ | j S )N)r,   r   )r/   r4   r4   r5   _get_namespace_managerD  s    

zGraph._get_namespace_managerc             C   s
   || _ d S )N)r,   )r/   nmr4   r4   r5   _set_namespace_managerI  s    zGraph._set_namespace_managerzthis graph's namespace-manager)docc             C   s   d| j t| f S )Nz<Graph identifier=%s (%s)>)r1   type)r/   r4   r4   r5   __repr__R  s    zGraph.__repr__c             C   s6   t | jtr$d| jj | jjjf S d| jjj S d S )Nz%s a rdfg:Graph;rdflib:storage z![a rdflib:Store;rdfs:label '%s'].z[a rdfg:Graph;rdflib:storage z"[a rdflib:Store;rdfs:label '%s']].z@%s a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s'].z?[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label '%s']].)r)   r1   r   n3r0   r3   __name__)r/   r4   r4   r5   __str__U  s
    zGraph.__str__c             C   s   | S )Nr4   )r/   r4   r4   r5   toPython_  s    zGraph.toPythonc             C   s   | j j| dS )z<Destroy the store identified by `configuration` if supportedN)r+   destroy)r/   configurationr4   r4   r5   r@   b  s    zGraph.destroyc             C   s   | j j  dS )zCommits active transactionsN)r+   commit)r/   r4   r4   r5   rB   g  s    zGraph.commitc             C   s   | j j  dS )zRollback active transactionsN)r+   rollback)r/   r4   r4   r5   rC   k  s    zGraph.rollbackFc             C   s   | 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/   rA   creater4   r4   r5   rD   o  s    z
Graph.openc             C   s   | j j|d dS )zClose the graph store

        Might be necessary for stores that require closing a connection to a
        database or releasing some resource.
        )commit_pending_transactionN)r+   close)r/   rF   r4   r4   r5   rG   w  s    zGraph.closec             C   sn   |\}}}t |ts"td|f t |ts:td|f t |tsRtd|f | jj|||f| dd dS )z!Add a triple with self as contextz!Subject %s must be an rdflib termz#Predicate %s must be an rdflib termz Object %s must be an rdflib termF)quotedN)r)   r   AssertionErrorr+   add)r/   triplespor4   r4   r5   rJ     s
    
z	Graph.addc                s    j j fdd|D  dS )z%Add a sequence of triple with contextc             3   sD   | ]<\}}}}t |tr|j jkrt|||r||||fV  qd S )N)r)   r   r1   _assertnode).0rL   rM   rN   c)r/   r4   r5   	<genexpr>  s   

zGraph.addN.<locals>.<genexpr>N)r+   addN)r/   quadsr4   )r/   r5   rS     s    
z
Graph.addNc             C   s   | j j|| d dS )zRemove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
        )contextN)r+   remove)r/   rK   r4   r4   r5   rV     s    zGraph.removec             c   sx   |\}}}t |tr>x^|j| ||D ]\}}|||fV  q$W n6x4| jj|||f| dD ]\\}}}}|||fV  qVW dS )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.
        )rU   N)r)   r   evalr+   triples)r/   rK   rL   rM   rN   Z_sZ_ocgr4   r4   r5   rX     s    

&zGraph.triplesc             C   s  t |tr|j|j|j  }}}|dkrH|dkrH|dkrH| j|||fS |dkrb|dkrb| j|S |dkr||dkr|| j|S |dkr|dkr| j|S |dkr| j	||S |dkr| j
||S |dkr| j||S |||f| kS n"t |ttf r| j|S tddS )a  
        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"), rdflib.RDFS.label, rdflib.Literal("Bob")))

        >>> 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[:rdflib.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

        NzWYou can only index a graph by a single rdflib term or path, or a slice of rdflib terms.)r)   slicestartstopsteprX   subject_predicatessubject_objectspredicate_objectssubjects
predicatesobjectsr   r   	TypeError)r/   itemrL   rM   rN   r4   r4   r5   __getitem__  s*    )




zGraph.__getitem__c             C   s   | j j| dS )zReturns the number of triples in the graph

        If context is specified then the number of triples in the context is
        returned instead.
        )rU   )r+   __len__)r/   r4   r4   r5   rg     s    zGraph.__len__c             C   s
   | j dS )z&Iterates over all triples in the storeN)NNN)rX   )r/   r4   r4   r5   __iter__  s    zGraph.__iter__c             C   s   x| j |D ]}dS W dS )z$Support for 'triple in graph' syntaxTF)rX   )r/   rK   r4   r4   r5   __contains__  s    zGraph.__contains__c             C   s
   t | jS )N)hashr1   )r/   r4   r4   r5   __hash__  s    zGraph.__hash__c             C   s6   |d krdS t |tr.| j|jk| j|jk  S dS d S )N   )r)   r   r1   )r/   otherr4   r4   r5   __cmp__  s    

zGraph.__cmp__c             C   s   t |to| j|jkS )N)r)   r   r1   )r/   rn   r4   r4   r5   __eq__  s    zGraph.__eq__c             C   s   |d kpt |to| j|jk S )N)r)   r   r1   )r/   rn   r4   r4   r5   __lt__  s    zGraph.__lt__c             C   s   | |k p| |kS )Nr4   )r/   rn   r4   r4   r5   __le__  s    zGraph.__le__c             C   s   t |tr| j|jkp|d k	S )N)r)   r   r1   )r/   rn   r4   r4   r5   __gt__  s    zGraph.__gt__c             C   s   | |kp| |kS )Nr4   )r/   rn   r4   r4   r5   __ge__!  s    zGraph.__ge__c                s    j  fdd|D   S )zNAdd all triples in Graph other to Graph.
           BNode IDs are not changed.c             3   s    | ]\}}}||| fV  qd S )Nr4   )rP   rL   rM   rN   )r/   r4   r5   rR   '  s    z!Graph.__iadd__.<locals>.<genexpr>)rS   )r/   rn   r4   )r/   r5   __iadd__$  s    zGraph.__iadd__c             C   s   x|D ]}| j | qW | S )zUSubtract all triples in Graph other from Graph.
           BNode IDs are not changed.)rV   )r/   rn   rK   r4   r4   r5   __isub__*  s    
zGraph.__isub__c             C   sp   t  }x4tt| j t|j  D ]\}}|j|| q$W x| D ]}|j| qBW x|D ]}|j| qZW |S )z9Set-theoretic union
           BNode IDs are not changed.)r   setlist
namespacesbindrJ   )r/   rn   retvalprefixurixyr4   r4   r5   __add__1  s    &

zGraph.__add__c             C   s*   t  }x|D ]}|| kr|j| qW |S )zASet-theoretic intersection.
           BNode IDs are not changed.)r   rJ   )r/   rn   r{   r~   r4   r4   r5   __mul__=  s
    
zGraph.__mul__c             C   s*   t  }x| D ]}||kr|j| qW |S )z?Set-theoretic difference.
           BNode IDs are not changed.)r   rJ   )r/   rn   r{   r~   r4   r4   r5   __sub__F  s
    
zGraph.__sub__c             C   s   | | ||   S )z8Set-theoretic XOR.
           BNode IDs are not changed.r4   )r/   rn   r4   r4   r5   __xor__O  s    zGraph.__xor__c             C   sN   |\}}}|dk	st d|dk	s*t d| j||df | j|||f d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, *, *))rI   rV   rJ   )r/   rK   subject	predicateobject_r4   r4   r5   rw   Y  s    


z	Graph.setc             c   s*   x$| j d||fD ]\}}}|V  qW dS )z;A generator of subjects with the given predicate and objectN)rX   )r/   r   objectrL   rM   rN   r4   r4   r5   ra   i  s    zGraph.subjectsc             c   s*   x$| j |d|fD ]\}}}|V  qW dS )z;A generator of predicates with the given subject and objectN)rX   )r/   r   r   rL   rM   rN   r4   r4   r5   rb   n  s    zGraph.predicatesc             c   s*   x$| j ||dfD ]\}}}|V  qW dS )z;A generator of objects with the given subject and predicateN)rX   )r/   r   r   rL   rM   rN   r4   r4   r5   rc   s  s    zGraph.objectsc             c   s.   x(| j dd|fD ]\}}}||fV  qW dS )z?A generator of (subject, predicate) tuples for the given objectN)rX   )r/   r   rL   rM   rN   r4   r4   r5   r^   x  s    zGraph.subject_predicatesc             c   s.   x(| j d|dfD ]\}}}||fV  qW dS )z?A generator of (subject, object) tuples for the given predicateN)rX   )r/   r   rL   rM   rN   r4   r4   r5   r_   }  s    zGraph.subject_objectsc             c   s.   x(| j |ddfD ]\}}}||fV  qW dS )z?A generator of (predicate, object) tuples for the given subjectN)rX   )r/   r   rL   rM   rN   r4   r4   r5   r`     s    zGraph.predicate_objectsc       
      c   sD   |\}}}x4| j j|||f| dD ]\\}}}}	|||fV  q"W d S )N)rU   )r0   triples_choices)
r/   rK   rU   r   r   r   rL   rM   rN   rY   r4   r4   r5   r     s    
zGraph.triples_choicesTc             C   s(  |}|dkr|dks4|dkr$|dks4|dkr8|dkr8dS |dkrL| j ||}|dkr`| j||}|dkrt| j||}yt|}W n tk
r   |}Y nX |dkr$yht| d|||f }| jj|||fd}	x.|	D ]&\\}
}}}|d|
||t|f 7 }qW tj	|W n tk
r"   Y nX |S )a  Get a value for a pair of two criteria

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

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

        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
        NFzYWhile trying to find a value for (%s, %s, %s) the following multiple values where found:
z(%s, %s, %s)
 (contexts: %s)
)
rc   ra   rb   nextStopIterationr0   rX   rx   r   ZUniquenessError)r/   r   r   r   r$   anyr{   valuesmsgrX   rL   rM   rN   contextsr4   r4   r5   value  s>    

zGraph.value c             C   s    |dkr|S | j |tj|ddS )z{Query for the RDFS.label of the subject

        Return default if no label exists or any label if multiple exist.
        NT)r$   r   )r   r   label)r/   r   r$   r4   r4   r5   r     s    zGraph.labelc                s   |dkrg }dk	r4dkr&dd }q<fdd}ndd }xD|D ]< t t|| j| }t|dkrlqBqB fdd	|D S qBW |S )
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, RDFS, Literal
        >>> from rdflib.namespace import SKOS
        >>> from pprint import pprint
        >>> g = ConjunctiveGraph()
        >>> u = URIRef("http://example.com/foo")
        >>> g.add([u, RDFS.label, Literal("foo")])
        >>> g.add([u, RDFS.label, Literal("bar")])
        >>> 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, SKOS.prefLabel, Literal("bla")])
        >>> pprint(g.preferredLabel(u))
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla'))]
        >>> g.add([u, SKOS.prefLabel, Literal("blubb", lang="en")])
        >>> 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'))]
        Nr   c             S   s
   | j d kS )N)language)lr4   r4   r5   
langfilter	  s    z(Graph.preferredLabel.<locals>.langfilterc                s
   | j  kS )N)r   )r   )langr4   r5   r     s    c             S   s   dS )NTr4   )r   r4   r4   r5   r     s    r   c                s   g | ]} |fqS r4   r4   )rP   r   )	labelPropr4   r5   
<listcomp>  s    z(Graph.preferredLabel.<locals>.<listcomp>)rx   filterrc   len)r/   r   r   r$   ZlabelPropertiesr   labelsr4   )r   r   r5   preferredLabel  s    0

zGraph.preferredLabelc             C   s    |dkr|S | j |tj|ddS )z_Query for the RDFS.comment of the subject

        Return default if no comment exists
        NT)r$   r   )r   r   comment)r/   r   r$   r4   r4   r5   r     s    zGraph.commentc             c   s\   t |g}xL|rV| j|tj}|dk	r,|V  | j|tj}||krJtd|j| qW dS )zgGenerator over all items in the resource specified by list

        list is an RDF collection.
        Nz,List contains a recursive rdf:rest reference)rw   r   r   firstrest
ValueErrorrJ   )r/   rx   chainre   r4   r4   r5   items'  s    
zGraph.itemsc             c   s^   |dkri }n||krdS d||< x6||| D ](}|V  x| j |||D ]
}|V  qHW q.W dS )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))
        >>> g.add((a,RDF.rest,b))
        >>> g.add((b,RDF.first,RDFS.label))
        >>> g.add((b,RDF.rest,c))
        >>> g.add((c,RDF.first,RDFS.comment))
        >>> g.add((c,RDF.rest,RDF.nil))
        >>> def topList(node,g):
        ...    for s in g.subjects(RDF.rest, node):
        ...       yield s
        >>> def reverseList(node,g):
        ...    for f in g.objects(node, RDF.first):
        ...       print(f)
        ...    for s in g.subjects(RDF.rest, node):
        ...       yield s

        >>> [rt for rt in g.transitiveClosure(
        ...     topList,RDF.nil)] # 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')]

        Nrl   )transitiveClosure)r/   funcargseenrtZrt_2r4   r4   r5   r   6  s    )zGraph.transitiveClosurec             c   s^   |dkri }||krdS d||< |V  x2| j ||D ]"}x| j|||D ]
}|V  qHW q4W dS )zTransitively generate objects for the ``property`` relationship

        Generated objects belong to the depth first transitive closure of the
        ``property`` relationship starting at ``subject``.
        Nrl   )rc   transitive_objects)r/   r   propertyrememberr   rN   r4   r4   r5   r   i  s    zGraph.transitive_objectsc             c   s^   |dkri }||krdS d||< |V  x2| j ||D ]"}x| j|||D ]
}|V  qHW q4W dS )zTransitively generate objects for the ``property`` relationship

        Generated objects belong to the depth first transitive closure of the
        ``property`` relationship starting at ``subject``.
        Nrl   )ra   transitive_subjects)r/   r   r   r   r   rL   r4   r4   r5   r   y  s    zGraph.transitive_subjectsc             C   s$   |t jt jf| krt| |S dS dS )ziCheck if subject is an rdf:Seq

        If yes, it returns a Seq class instance, None otherwise.
        N)r   r:   r   )r/   r   r4   r4   r5   seq  s    
z	Graph.seqc             C   s   | j j|S )N)r2   qname)r/   r}   r4   r4   r5   r     s    zGraph.qnamec             C   s   | j j||S )N)r2   compute_qname)r/   r}   generater4   r4   r5   r     s    zGraph.compute_qnamec             C   s   | j j||||d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   rz   )r/   r|   	namespacer   r   r4   r4   r5   rz     s    z
Graph.bindc             c   s&   x | j j D ]\}}||fV  qW dS )z/Generator over all the prefix, namespace tuplesN)r2   ry   )r/   r|   r   r4   r4   r5   ry     s    zGraph.namespacesrl   c             C   s   | j j||S )z5Turn uri into an absolute URI if it's not one already)r2   
absolutize)r/   r}   defragr4   r4   r5   r     s    zGraph.absolutizexmlc             K   s
  |dkr| j }tj|t| }|dkrLt }|j|f||d| |j S t|drt|}|j|f||d| n|}t|\}	}
}}}}|
dkrt	d	 dS t
j \}}tj|d}|j|f||d| |j  ttdrtj|| ntj|| tj| dS )
aH  Serialize the Graph to destination

        If destination is None serialize method returns the serialization as a
        string. Format defaults to xml (AKA rdf/xml).

        Format support can be extended with plugins,
        but "xml", "n3", "turtle", "nt", "pretty-xml", "trix", "trig" and "nquads" are built in.
        N)r'   encodingwriter   zWARNING: not saving as locationzis not a local file referencewbmovez<WARNING: not saving as locationis not a local file reference)r'   r
   r*   r   r   	serializegetvaluehasattrr   printtempfilemkstemposfdopenrG   shutilr   copyrV   )r/   Zdestinationformatr'   r   args
serializerstreamlocationschemenetlocpathparamsZ_queryfragmentfdnamer4   r4   r5   r     s0    

zGraph.serializec       	   
   K   sf   t ||||||d}|dkr"|j}|dkr.d}tj|t }z|j|| f| W d|jr`|j  X | S )a  
        Parse 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.
            Defaults to rdf/xml. Format support can be extended with plugins,
            but "xml", "n3", "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 on py3
        >>> 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)

        )sourcepublicIDr   filedatar   Nzapplication/rdf+xml)r   content_typer
   r*   r   parseZ
auto_closerG   )	r/   r   r   r   r   r   r   r   parserr4   r4   r5   r     s"    K
zGraph.parsec             C   s   | j ||| d S )N)r   )r/   r   r   r   r4   r4   r5   load<  s    z
Graph.loadsparqlc             K   s   |pi }|pt | j }t| jdr`|r`y"| jj|||| jr@dpD| jf|S  tk
r^   Y nX t|tj	szt
j|tj	}t|tjst
j|tj| }||j|||f|S )au  
        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.QueryResult

        r   	__UNION__)dictry   r   r0   r   r.   r1   NotImplementedErrorr)   ZResultr
   r*   Z	Processor)r/   Zquery_object	processorresultinitNsinitBindingsuse_store_providedkwargsr4   r4   r5   r   ?  s"    zGraph.queryc             K   s   |pi }|pt | j }t| jdr`|r`y"| jj|||| jr@dpD| jf|S  tk
r^   Y nX t|t	j
s~tj|t	j
| }|j|||f|S )z.Update this graph with the given update query.updater   )r   ry   r   r0   r   r.   r1   r   r)   r   ZUpdateProcessorr
   r*   )r/   Zupdate_objectr   r   r   r   r   r4   r4   r5   r   m  s    
zGraph.updatec             C   s   d| j j  S )z%return an n3 identifier for the Graphz[%s])r1   r<   )r/   r4   r4   r5   r<     s    zGraph.n3c             C   s   t | j| jffS )N)r   r0   r1   )r/   r4   r4   r5   
__reduce__  s    zGraph.__reduce__c             C   s   t | t |krdS x<| D ]4\}}}t|t rt|t r|||f|krdS qW x<|D ]4\}}}t|t rXt|t rX|||f| krXdS qXW dS )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   r)   r   )r/   rn   rL   rM   rN   r4   r4   r5   
isomorphic  s    zGraph.isomorphicc             C   s   t | j }g }|sdS |tjt| g}x|r|j }||krL|j| x.| j|dD ]}||krZ||krZ|j| qZW x.| j|dD ]}||kr||kr|j| qW q.W t|t|krdS dS dS )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   TN)	rx   	all_nodesrandom	randranger   popappendrc   ra   )r/   r   Z
discoveredZvisitingr~   Znew_xr4   r4   r5   	connected  s$    

zGraph.connectedc             C   s   t | j }|j| j  |S )N)rw   rc   r   ra   )r/   resr4   r4   r5   r     s    zGraph.all_nodesc             C   s
   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   r4   r4   r5   
collection  s    zGraph.collectionc             C   s   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

        )r)   r   r   r   )r/   r1   r4   r4   r5   resource  s    
zGraph.resourcec             C   s&   x | j dD ]}|j|| qW d S )N)NNN)rX   rJ   )r/   targetr   tr4   r4   r5   _process_skolem_tuples  s    zGraph._process_skolem_tuplesc                sh    fdd fdd}|d kr*t  n|}d krD| j|| n ttrd| j|fdd |S )Nc                s@   |\}}}|| kr |j  d}|| kr6|j  d}|||fS )N)	authoritybasepath)	skolemize)bnoder   rL   rM   rN   )r   r   r4   r5   do_skolemize  s    
z%Graph.skolemize.<locals>.do_skolemizec                sD   | \}}}t |tr"|j d}t |tr:|j d}|||fS )N)r   r   )r)   r   r   )r   rL   rM   rN   )r   r   r4   r5   do_skolemize2  s    


z&Graph.skolemize.<locals>.do_skolemize2c                s
    | S )Nr4   )r   )r   r   r4   r5   <lambda>  s    z!Graph.skolemize.<locals>.<lambda>)r   r   r)   r   )r/   	new_graphr   r   r   r   r{   r4   )r   r   r   r   r5   r     s    
zGraph.skolemizec                s\   dd  dd }|d krt  n|}d kr8| j|| n ttrX| j| fdd |S )Nc             S   s4   |\}}}|| kr|j  }|| kr*|j  }|||fS )N)de_skolemize)urirefr   rL   rM   rN   r4   r4   r5   do_de_skolemize  s    
z+Graph.de_skolemize.<locals>.do_de_skolemizec             S   s8   | \}}}t |tr|j }t |tr.|j }|||fS )N)r)   r   r   )r   rL   rM   rN   r4   r4   r5   do_de_skolemize2!  s    


z,Graph.de_skolemize.<locals>.do_de_skolemize2c                s
    | S )Nr4   )r   )r   r   r4   r5   r   .  s    z$Graph.de_skolemize.<locals>.<lambda>)r   r   r)   r   )r/   r   r   r   r{   r4   )r   r   r5   r     s    
zGraph.de_skolemize)r$   NNN)F)F)NN)NN)NN)N)N)N)N)r   )r   )N)N)N)T)TF)rl   )Nr   NN)NNNNNN)Nr   )r   r   NNT)r   NNT)NNNN)NN)Vr=   
__module____qualname____doc__r&   Z_Graph__get_storer   r0   Z_Graph__get_identifierr1   r6   r8   r2   r;   r>   r?   r@   rB   rC   rD   rG   rJ   rS   rV   rX   rf   rg   rh   ri   rk   ro   rp   rq   rr   rs   rt   ru   rv   r   r   r   r   __or____and__rw   ra   rb   rc   r^   r_   r`   r   r   r   r   r	   Z	prefLabelr   r   r   r   r   r   r   r   r   r   rz   ry   r   r   r   r   r   r   r<   r   r   r   r   r   r   r   r   r   __classcell__r4   r4   )r3   r5   r     s   


G		






:
G
	
3






+     
Z
    
*   
%
c                   s   e Zd ZdZd* fdd	Zdd Zd+d	d
Zdd Zdd Zdd Z	dd Z
dd Zd,ddZd-ddZd.ddZdd Zd/ddZd0dd Zd!d" Zd1d#d$Zd2d&d'Zd(d) Z  ZS )3r   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$   Nc                sL   t t| j||d | jjs$tdd| _d| _t| j|p>t |d| _	d S )N)r1   z9ConjunctiveGraph must be backed by a context aware store.T)r0   r1   r'   )
r%   r   r&   r0   r-   rI   r.   r   r   default_context)r/   r0   r1   default_graph_base)r3   r4   r5   r&   A  s    
zConjunctiveGraph.__init__c             C   s   d}|| j jj S )NzK[a rdflib:ConjunctiveGraph;rdflib:storage [a rdflib:Store;rdfs:label '%s']])r0   r3   r=   )r/   patternr4   r4   r5   r>   L  s    zConjunctiveGraph.__str__Fc             C   sr   |dkrddd|r| j ndfS t|dkrD|r4| j nd}|\}}}n"t|dkrf|\}}}}| j|}||||fS )z_
        helper method for having methods that support
        either triples or quads
        N      )r  r   _graph)r/   triple_or_quadr$   rQ   rL   rM   rN   r4   r4   r5   _spocS  s    
zConjunctiveGraph._spocc             C   s6   | j |\}}}}x| j|||f|dD ]}dS W dS )z)Support for 'triple/quad in graph' syntax)rU   TF)r	  rX   )r/   r  rL   rM   rN   rQ   r   r4   r4   r5   ri   b  s    zConjunctiveGraph.__contains__c             C   s>   | j |dd\}}}}t||| | jj|||f|dd 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)rU   rH   N)r	  rO   r0   rJ   )r/   r  rL   rM   rN   rQ   r4   r4   r5   rJ   i  s    zConjunctiveGraph.addc             C   s(   |d krd S t |ts | j|S |S d S )N)r)   r   get_context)r/   rQ   r4   r4   r5   r  v  s
    

zConjunctiveGraph._graphc                s    j j fdd|D  dS )z&Add a sequence of triples with contextc             3   s4   | ],\}}}}t |||r||| j|fV  qd S )N)rO   r  )rP   rL   rM   rN   rQ   )r/   r4   r5   rR     s    z(ConjunctiveGraph.addN.<locals>.<genexpr>N)r0   rS   )r/   rT   r4   )r/   r5   rS   ~  s    zConjunctiveGraph.addNc             C   s,   | j |\}}}}| jj|||f|d d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

        )rU   N)r	  r0   rV   )r/   r  rL   rM   rN   rQ   r4   r4   r5   rV     s    	zConjunctiveGraph.removec             c   s   | j |\}}}}| j|p|}| jr6|| jkrDd}n|dkrD| j}t|tr|dkrZ| }x^|j|||D ]\}}|||fV  qjW n6x4| jj|||f|dD ]\\}}}}|||fV  qW dS )a  
        Iterate over all the triples in the entire conjunctive graph

        For legacy reasons, this can take the context to query either
        as a fourth element of the quad, or as the explicit context
        keyword parameter. The kw param takes precedence.
        N)rU   )	r	  r  r.   r  r)   r   rW   r0   rX   )r/   r  rU   rL   rM   rN   rQ   rY   r4   r4   r5   rX     s    	

&zConjunctiveGraph.triplesc             c   s\   | j |\}}}}xD| jj|||f|dD ]*\\}}}}x|D ]}||||fV  q>W q*W dS )z:Iterate over all the quads in the entire conjunctive graph)rU   N)r	  r0   rX   )r/   r  rL   rM   rN   rQ   rY   ctxr4   r4   r5   rT     s    &
zConjunctiveGraph.quadsc       
      c   sd   |\}}}|dkr | j s*| j}n
| j|}x4| jj|||f|dD ]\\}}}}	|||fV  qBW dS )z<Iterate over all the triples in the entire conjunctive graphN)rU   )r.   r  r  r0   r   )
r/   rK   rU   rL   rM   rN   s1p1o1rY   r4   r4   r5   r     s    

&z ConjunctiveGraph.triples_choicesc             C   s
   | j j S )z1Number of triples in the entire conjunctive graph)r0   rg   )r/   r4   r4   r5   rg     s    zConjunctiveGraph.__len__c             c   s8   x2| j j|D ]"}t|tr$|V  q| j|V  qW dS )z|Iterate over all contexts in the graph

        If triple is specified, iterate over all contexts the triple is in.
        N)r0   r   r)   r   r
  )r/   rK   rU   r4   r4   r5   r     s    
zConjunctiveGraph.contextsc             C   s   t | j|| |dS )zgReturn a context graph for the given identifier

        identifier must be a URIRef or BNode.
        )r0   r1   r2   r'   )r   r0   )r/   r1   rH   r'   r4   r4   r5   r
    s    zConjunctiveGraph.get_contextc             C   s   | j jd| dS )z(Removes the given context from the graphN)NNN)r0   rV   )r/   rU   r4   r4   r5   remove_context  s    zConjunctiveGraph.remove_contextc             C   s(   |j ddd }|dkrd}t||dS )zURI#context#rl   r   Nz#context)r'   )splitr   )r/   r}   
context_idr4   r4   r5   r    s    zConjunctiveGraph.context_idr   c       
      K   sj   t ||||||d}|r|p"|j }t|ts6t|}t| j|d}	|	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   r   r   r   r   r   )r0   r1   N)r   r   )NNN)	r   getPublicIdr)   r   r   r   r0   rV   r   )
r/   r   r   r   r   r   r   r   Zg_idrU   r4   r4   r5   r     s    

zConjunctiveGraph.parsec             C   s   t | j| jffS )N)r   r0   r1   )r/   r4   r4   r5   r     s    zConjunctiveGraph.__reduce__)r$   NN)F)N)N)N)N)FN)N)NNr   NNN)r=   r   r   r   r&   r>   r	  ri   rJ   r  rS   rV   rX   rT   r   rg   r   r
  r  r  r   r   r  r4   r4   )r3   r5   r   3  s0   


	



	     
!zurn:x-rdflib:defaultc                   sl   e Zd ZdZd fdd	Zdd Zdd	d
ZdddZdd Zdd Z	d fdd	Z
e
Z fddZ  ZS )r!   aV  
    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")))
    >>>
    >>> # 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")) )
    >>> # 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) )
    >>>
    >>> # 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
    >>> # 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"))
    >>>
    >>> 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
    r$   FNc                s@   t t| j|d d | jjs$tdt| jt|d| _|| _	d S )N)r0   r1   z.DataSet must be backed by a graph-aware store!)r0   r1   r'   )
r%   r!   r&   r0   Zgraph_aware	Exceptionr   DATASET_DEFAULT_GRAPH_IDr  r.   )r/   r0   r.   r  )r3   r4   r5   r&   ~  s    zDataset.__init__c             C   s   d}|| j jj S )NzB[a rdflib:Dataset;rdflib:storage [a rdflib:Store;rdfs:label '%s']])r0   r3   r=   )r/   r  r4   r4   r5   r>     s    zDataset.__str__c             C   sR   |d kr2ddl m} | jdd| dd t j }| j|}||_| jj| |S )Nr   )rdflib_skolem_genidZgenidzhttp://rdflib.netF)r   )	rdflib.termr  rz   r   r   r  r'   r0   	add_graph)r/   r1   r'   r  gr4   r4   r5   graph  s    

zDataset.graphr   c       	      K   s(   t j| ||||||f|}| j| |S )N)r   r   r  )	r/   r   r   r   r   r   r   r   rQ   r4   r4   r5   r     s    

zDataset.parsec             C   s
   | j |S )zalias of graph for consistency)r  )r/   r  r4   r4   r5   r    s    zDataset.add_graphc             C   sD   t |ts| j|}| jj| |d ks2|| jkr@| jj| j d S )N)r)   r   r
  r0   remove_graphr  r  )r/   r  r4   r4   r5   r    s
    

zDataset.remove_graphc             #   sF   d}x,t t| j|D ]}||jtkO }|V  qW |sB| jtV  d S )NF)r%   r!   r   r1   r  r  )r/   rK   r$   rQ   )r3   r4   r5   r     s    
zDataset.contextsc             #   sR   xLt t| j|D ]8\}}}}|j| jkr:|||d fV  q||||jfV  qW d S )N)r%   r!   rT   r1   r  )r/   ZquadrL   rM   rN   rQ   )r3   r4   r5   rT     s    zDataset.quads)r$   FN)NN)NNr   NNN)N)r=   r   r   r   r&   r>   r  r   r  r  r   graphsrT   r  r4   r4   )r3   r5   r!     s   e
     
	
c                   sH   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Zdd Z	  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                s   t t| j|| d S )N)r%   r   r&   )r/   r0   r1   )r3   r4   r5   r&     s    zQuotedGraph.__init__c             C   sn   |\}}}t |ts"td|f t |ts:td|f t |tsRtd|f | jj|||f| dd dS )z!Add a triple with self as contextz!Subject %s must be an rdflib termz#Predicate %s must be an rdflib termz Object %s must be an rdflib termT)rH   N)r)   r   rI   r0   rJ   )r/   rK   rL   rM   rN   r4   r4   r5   rJ     s
    
zQuotedGraph.addc                s    j j fdd|D  dS )z%Add a sequence of triple with contextc             3   sD   | ]<\}}}}t |tr|j jkrt|||r||||fV  qd S )N)r)   r   r1   rO   )rP   rL   rM   rN   rQ   )r/   r4   r5   rR     s   

z#QuotedGraph.addN.<locals>.<genexpr>N)r0   rS   )r/   rT   r4   )r/   r5   rS     s    
zQuotedGraph.addNc             C   s   d| j j  S )z%Return an n3 identifier for the Graphz{%s})r1   r<   )r/   r4   r4   r5   r<     s    zQuotedGraph.n3c             C   s$   | j j }| jjj}d}|||f S )NzK{this rdflib.identifier %s;rdflib:storage [a rdflib:Store;rdfs:label '%s']})r1   r<   r0   r3   r=   )r/   r1   r   r  r4   r4   r5   r>     s    

zQuotedGraph.__str__c             C   s   t | j| jffS )N)r   r0   r1   )r/   r4   r4   r5   r     s    zQuotedGraph.__reduce__)r=   r   r   r   r&   rJ   rS   r<   r>   r   r  r4   r4   )r3   r5   r     s   		   c               @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )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             C   sh   t   }| _tttd }x>|j|D ]0\}}|j|r(t|j|d}|j	||f q(W |j
  dS )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)rx   _listr   strr   r`   
startswithintr   r   sort)r/   r  r   r  ZLI_INDEXrM   rN   ir4   r4   r5   r&     s    
zSeq.__init__c             C   s   | S )Nr4   )r/   r4   r4   r5   r?   %  s    zSeq.toPythonc             c   s   x| j D ]\}}|V  qW dS )z#Generator over the items in the SeqN)r  )r/   r  re   r4   r4   r5   rh   (  s    zSeq.__iter__c             C   s
   t | jS )zLength of the Seq)r   r  )r/   r4   r4   r5   rg   -  s    zSeq.__len__c             C   s   | j j|\}}|S )z Item given by index from the Seq)r  rf   )r/   indexre   r4   r4   r5   rf   1  s    zSeq.__getitem__N)	r=   r   r   r   r&   r?   rh   rg   rf   r4   r4   r4   r5   r     s   c               @   s   e Zd Zdd Zdd ZdS )r    c             C   s   d S )Nr4   )r/   r4   r4   r5   r&   8  s    zModificationException.__init__c             C   s   dS )NzZModifications and transactional operations not allowed on ReadOnlyGraphAggregate instancesr4   )r/   r4   r4   r5   r>   ;  s    zModificationException.__str__N)r=   r   r   r&   r>   r4   r4   r4   r5   r    7  s   c               @   s   e Zd Zdd Zdd ZdS )r"   c             C   s   d S )Nr4   )r/   r4   r4   r5   r&   C  s    z&UnSupportedAggregateOperation.__init__c             C   s   dS )NzCThis operation is not supported by ReadOnlyGraphAggregate instancesr4   )r/   r4   r4   r5   r>   F  s    z%UnSupportedAggregateOperation.__str__N)r=   r   r   r&   r>   r4   r4   r4   r5   r"   B  s   c                   s   e Zd ZdZd> fdd	Zdd Zdd Zd	d
 Zdd Zd?ddZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd@d)d*Zd+d, ZdAd.d/ZdBd0d1Zd2d3 ZdCd5d6ZdDd8d9Zd:d; Zd<d= Z  ZS )Er#   zUtility class for treating a set of graphs as a single graph

    Only read operations are supported (hence the name). Essentially a
    ConjunctiveGraph over an explicit subset of the entire store.
    r$   c                sX   |d k	r*t t| j| tj| | d | _t|trF|rFdd |D sNtd|| _d S )Nc             S   s   g | ]}t |tr|qS r4   )r)   r   )rP   r  r4   r4   r5   r   Z  s    z3ReadOnlyGraphAggregate.__init__.<locals>.<listcomp>z*graphs argument must be a list of Graphs!!)	r%   r#   r&   r   Z*_ReadOnlyGraphAggregate__namespace_managerr)   rx   rI   r  )r/   r  r0   )r3   r4   r5   r&   Q  s    
zReadOnlyGraphAggregate.__init__c             C   s   dt | j S )Nz#<ReadOnlyGraphAggregate: %s graphs>)r   r  )r/   r4   r4   r5   r;   ^  s    zReadOnlyGraphAggregate.__repr__c             C   s
   t  d S )N)r    )r/   rA   r4   r4   r5   r@   a  s    zReadOnlyGraphAggregate.destroyc             C   s
   t  d S )N)r    )r/   r4   r4   r5   rB   e  s    zReadOnlyGraphAggregate.commitc             C   s
   t  d S )N)r    )r/   r4   r4   r5   rC   h  s    zReadOnlyGraphAggregate.rollbackFc             C   s"   x| j D ]}|j| || qW d S )N)r  rD   )r/   rA   rE   r  r4   r4   r5   rD   k  s    zReadOnlyGraphAggregate.openc             C   s   x| j D ]}|j  qW d S )N)r  rG   )r/   r  r4   r4   r5   rG   p  s    zReadOnlyGraphAggregate.closec             C   s
   t  d S )N)r    )r/   rK   r4   r4   r5   rJ   t  s    zReadOnlyGraphAggregate.addc             C   s
   t  d S )N)r    )r/   rT   r4   r4   r5   rS   w  s    zReadOnlyGraphAggregate.addNc             C   s
   t  d S )N)r    )r/   rK   r4   r4   r5   rV   z  s    zReadOnlyGraphAggregate.removec       	      c   s~   |\}}}xn| j D ]d}t|trJxT|j| ||D ]\}}|||fV  q0W qx*|j|||fD ]\}}}|||fV  q\W qW d S )N)r  r)   r   rW   rX   )	r/   rK   rL   rM   rN   r  r  r  r  r4   r4   r5   rX   }  s    

zReadOnlyGraphAggregate.triplesc             C   sT   d }t |dkr|d }x6| jD ],}|d ks8|j|jkr |d d |kr dS q W dS )Nr  r  TF)r   r  r1   )r/   r  rU   r  r4   r4   r5   ri     s    z#ReadOnlyGraphAggregate.__contains__c       	      c   sL   |\}}}x<| j D ]2}x,|j|||fD ]\}}}||||fV  q(W qW dS )z8Iterate over all the quads in the entire aggregate graphN)r  rX   )	r/   rK   rL   rM   rN   r  r  r  r  r4   r4   r5   rT     s    
zReadOnlyGraphAggregate.quadsc             C   s   t dd | jD S )Nc             s   s   | ]}t |V  qd S )N)r   )rP   r  r4   r4   r5   rR     s    z1ReadOnlyGraphAggregate.__len__.<locals>.<genexpr>)sumr  )r/   r4   r4   r5   rg     s    zReadOnlyGraphAggregate.__len__c             C   s
   t  d S )N)r"   )r/   r4   r4   r5   rk     s    zReadOnlyGraphAggregate.__hash__c             C   sD   |d krdS t |trdS t |tr<| j|jk| j|jk  S dS d S )Nrl   rm   rm   rm   )r)   r   r#   r  )r/   rn   r4   r4   r5   ro     s    

zReadOnlyGraphAggregate.__cmp__c             C   s
   t  d S )N)r    )r/   rn   r4   r4   r5   ru     s    zReadOnlyGraphAggregate.__iadd__c             C   s
   t  d S )N)r    )r/   rn   r4   r4   r5   rv     s    zReadOnlyGraphAggregate.__isub__Nc             c   sN   |\}}}x>| j D ]4}|j|||f}x|D ]\}}	}
||	|
fV  q,W qW d S )N)r  r   )r/   rK   rU   r   r   r   r  choicesrL   rM   rN   r4   r4   r5   r     s
    
z&ReadOnlyGraphAggregate.triples_choicesc             C   s&   t | dr| jr| jj|S t d S )Nr2   )r   r2   r   r"   )r/   r}   r4   r4   r5   r     s    zReadOnlyGraphAggregate.qnameTc             C   s(   t | dr| jr| jj||S t d S )Nr2   )r   r2   r   r"   )r/   r}   r   r4   r4   r5   r     s    z$ReadOnlyGraphAggregate.compute_qnamec             C   s
   t  d S )N)r"   )r/   r|   r   r   r4   r4   r5   rz     s    zReadOnlyGraphAggregate.bindc             c   sb   t | dr.xR| jj D ]\}}||fV  qW n0x.| jD ]$}x|j D ]\}}||fV  qDW q6W d S )Nr2   )r   r2   ry   r  )r/   r|   r   r  r4   r4   r5   ry     s    
z!ReadOnlyGraphAggregate.namespacesrl   c             C   s
   t  d S )N)r"   )r/   r}   r   r4   r4   r5   r     s    z!ReadOnlyGraphAggregate.absolutizer   c             K   s
   t  d S )N)r    )r/   r   r   r   r   r4   r4   r5   r     s    zReadOnlyGraphAggregate.parsec             C   s
   t  d S )N)r"   )r/   r4   r4   r5   r<     s    zReadOnlyGraphAggregate.n3c             C   s
   t  d S )N)r"   )r/   r4   r4   r5   r     s    z!ReadOnlyGraphAggregate.__reduce__)r$   )F)N)T)T)rl   )Nr   ) r=   r   r   r   r&   r;   r@   rB   rC   rD   rG   rJ   rS   rV   rX   ri   rT   rg   rk   ro   ru   rv   r   r   r   rz   ry   r   r   r<   r   r  r4   r4   )r3   r5   r#   J  s8   






	

c              G   s*   x$| D ]}t |tstd|f qW dS )NzTerm %s must be an rdflib termT)r)   r   rI   )Ztermsr   r4   r4   r5   rO     s    
rO   c              C   s   dd l } | j  d S )Nr   )doctesttestmod)r(  r4   r4   r5   test  s    r*  __main__)@
__future__r   r   r   r  r   rI   Zrdflib.namespacer   r   logging	getLoggerr=   loggerr   r   r   r	   Zrdflibr
   r   r   r   r   r   r   Zrdflib.pathsr   Zrdflib.storer   Zrdflib.serializerr   Zrdflib.parserr   r   r   Zrdflib.resourcer   Zrdflib.collectionr   r   r   r   sixr   r   Zsix.moves.urllib.parser   __all__r   r   r  r!   r   ZtermZ	_ORDERINGr   r   r  r    r"   r#   rO   r*  r4   r4   r4   r5   <module>   s~    c
        & b 842 
