
    4Ysh9                     P    d Z ddlmZmZmZ ddlmZ ddlmZ dgZ	 G d de
      Zy)a$  
The :class:`~rdflib.resource.Resource` class wraps a
:class:`~rdflib.graph.Graph`
and a resource reference (i.e. a :class:`rdflib.term.URIRef` or
:class:`rdflib.term.BNode`) to support a resource-oriented way of
working with a graph.

It contains methods directly corresponding to those methods of the Graph
interface that relate to reading and writing data. The difference is that a
Resource also binds a resource identifier, making it possible to work without
tracking both the graph and a current subject. This makes for a "resource
oriented" style, as compared to the triple orientation of the Graph API.

Resulting generators are also wrapped so that any resource reference values
(:class:`rdflib.term.URIRef`s and :class:`rdflib.term.BNode`s) are in turn
wrapped as Resources. (Note that this behaviour differs from the corresponding
methods in :class:`~rdflib.graph.Graph`, where no such conversion takes place.)


Basic Usage Scenario
--------------------

Start by importing things we need and define some namespaces::

    >>> from rdflib import *
    >>> FOAF = Namespace("http://xmlns.com/foaf/0.1/")
    >>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#")

Load some RDF data::

    >>> graph = Graph().parse(format='n3', data='''
    ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    ... @prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
    ... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
    ... @prefix cv: <http://purl.org/captsolo/resume-rdf/0.2/cv#> .
    ...
    ... @base <http://example.org/> .
    ...
    ... </person/some1#self> a foaf:Person;
    ...     rdfs:comment "Just a Python & RDF hacker."@en;
    ...     foaf:depiction </images/person/some1.jpg>;
    ...     foaf:homepage <http://example.net/>;
    ...     foaf:name "Some Body" .
    ...
    ... </images/person/some1.jpg> a foaf:Image;
    ...     rdfs:label "some 1"@en;
    ...     rdfs:comment "Just an image"@en;
    ...     foaf:thumbnail </images/person/some1-thumb.jpg> .
    ...
    ... </images/person/some1-thumb.jpg> a foaf:Image .
    ...
    ... [] a cv:CV;
    ...     cv:aboutPerson </person/some1#self>;
    ...     cv:hasWorkHistory [ cv:employedIn </#company>;
    ...             cv:startDate "2009-09-04"^^xsd:date ] .
    ... ''')

Create a Resource::

    >>> person = Resource(
    ...     graph, URIRef("http://example.org/person/some1#self"))

Retrieve some basic facts::

    >>> person.identifier
    rdflib.term.URIRef(u'http://example.org/person/some1#self')

    >>> person.value(FOAF.name)
    rdflib.term.Literal(u'Some Body')

    >>> person.value(RDFS.comment)
    rdflib.term.Literal(u'Just a Python & RDF hacker.', lang=u'en')

Resources can be sliced (like graphs, but the subject is fixed)::

    >>> for name in person[FOAF.name]:
    ...     print(name)
    Some Body
    >>> person[FOAF.name : Literal("Some Body")]
    True

Resources as unicode are represented by their identifiers as unicode::

    >>> %(unicode)s(person)  #doctest: +SKIP
    u'Resource(http://example.org/person/some1#self'

Resource references are also Resources, so you can easily get e.g. a qname
for the type of a resource, like::

    >>> person.value(RDF.type).qname()
    u'foaf:Person'

Or for the predicates of a resource::

    >>> sorted(
    ...     p.qname() for p in person.predicates()
    ... )  #doctest: +NORMALIZE_WHITESPACE +SKIP
    [u'foaf:depiction', u'foaf:homepage',
     u'foaf:name', u'rdf:type', u'rdfs:comment']

Follow relations and get more data from their Resources as well::

    >>> for pic in person.objects(FOAF.depiction):
    ...     print(pic.identifier)
    ...     print(pic.value(RDF.type).qname())
    ...     print(pic.label())
    ...     print(pic.comment())
    ...     print(pic.value(FOAF.thumbnail).identifier)
    http://example.org/images/person/some1.jpg
    foaf:Image
    some 1
    Just an image
    http://example.org/images/person/some1-thumb.jpg

    >>> for cv in person.subjects(CV.aboutPerson):
    ...     work = list(cv.objects(CV.hasWorkHistory))[0]
    ...     print(work.value(CV.employedIn).identifier)
    ...     print(work.value(CV.startDate))
    http://example.org/#company
    2009-09-04

It's just as easy to work with the predicates of a resource::

    >>> for s, p in person.subject_predicates():
    ...     print(s.value(RDF.type).qname())
    ...     print(p.qname())
    ...     for s, o in p.subject_objects():
    ...         print(s.value(RDF.type).qname())
    ...         print(o.value(RDF.type).qname())
    cv:CV
    cv:aboutPerson
    cv:CV
    foaf:Person

This is useful for e.g. inspection::

    >>> thumb_ref = URIRef("http://example.org/images/person/some1-thumb.jpg")
    >>> thumb = Resource(graph, thumb_ref)
    >>> for p, o in thumb.predicate_objects():
    ...     print(p.qname())
    ...     print(o.qname())
    rdf:type
    foaf:Image

Similarly, adding, setting and removing data is easy::

    >>> thumb.add(RDFS.label, Literal("thumb"))
    >>> print(thumb.label())
    thumb
    >>> thumb.set(RDFS.label, Literal("thumbnail"))
    >>> print(thumb.label())
    thumbnail
    >>> thumb.remove(RDFS.label)
    >>> list(thumb.objects(RDFS.label))
    []


Schema Example
--------------

With this artificial schema data::

    >>> graph = Graph().parse(format='n3', data='''
    ... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    ... @prefix owl: <http://www.w3.org/2002/07/owl#> .
    ... @prefix v: <http://example.org/def/v#> .
    ...
    ... v:Artifact a owl:Class .
    ...
    ... v:Document a owl:Class;
    ...     rdfs:subClassOf v:Artifact .
    ...
    ... v:Paper a owl:Class;
    ...     rdfs:subClassOf v:Document .
    ...
    ... v:Choice owl:oneOf (v:One v:Other) .
    ...
    ... v:Stuff a rdf:Seq; rdf:_1 v:One; rdf:_2 v:Other .
    ...
    ... ''')

From this class::

    >>> artifact = Resource(graph, URIRef("http://example.org/def/v#Artifact"))

we can get at subclasses::

    >>> subclasses = list(artifact.transitive_subjects(RDFS.subClassOf))
    >>> [c.qname() for c in subclasses]
    [u'v:Artifact', u'v:Document', u'v:Paper']

and superclasses from the last subclass::

    >>> [c.qname() for c in subclasses[-1].transitive_objects(RDFS.subClassOf)]
    [u'v:Paper', u'v:Document', u'v:Artifact']

Get items from the Choice::

    >>> choice = Resource(graph, URIRef("http://example.org/def/v#Choice"))
    >>> [it.qname() for it in choice.value(OWL.oneOf).items()]
    [u'v:One', u'v:Other']

And the sequence of Stuff::

    >>> stuff = Resource(graph, URIRef("http://example.org/def/v#Stuff"))
    >>> [it.qname() for it in stuff.seq()]
    [u'v:One', u'v:Other']

On add, other resources are auto-unboxed:
    >>> paper = Resource(graph, URIRef("http://example.org/def/v#Paper"))
    >>> paper.add(RDFS.subClassOf, artifact)
    >>> artifact in paper.objects(RDFS.subClassOf) # checks Resource instance
    True
    >>> (paper._identifier, RDFS.subClassOf, artifact._identifier) in graph
    True


Technical Details
-----------------

Comparison is based on graph and identifier::

    >>> g1 = Graph()
    >>> t1 = Resource(g1, URIRef("http://example.org/thing"))
    >>> t2 = Resource(g1, URIRef("http://example.org/thing"))
    >>> t3 = Resource(g1, URIRef("http://example.org/other"))
    >>> t4 = Resource(Graph(), URIRef("http://example.org/other"))

    >>> t1 is t2
    False

    >>> t1 == t2
    True
    >>> t1 != t2
    False

    >>> t1 == t3
    False
    >>> t1 != t3
    True

    >>> t3 != t4
    True

    >>> t3 < t1 and t1 > t3
    True
    >>> t1 >= t1 and t1 >= t3
    True
    >>> t1 <= t1 and t3 <= t1
    True

    >>> t1 < t1 or t1 < t3 or t3 > t1 or t3 > t3
    False

Hash is computed from graph and identifier::

    >>> g1 = Graph()
    >>> t1 = Resource(g1, URIRef("http://example.org/thing"))

    >>> hash(t1) == hash(Resource(g1, URIRef("http://example.org/thing")))
    True

    >>> hash(t1) == hash(Resource(Graph(), t1.identifier))
    False
    >>> hash(t1) == hash(Resource(Graph(), URIRef("http://example.org/thing")))
    False

The Resource class is suitable as a base class for mapper toolkits. For
example, consider this utility for accessing RDF properties via qname-like
attributes::

    >>> class Item(Resource):
    ...
    ...     def __getattr__(self, p):
    ...         return list(self.objects(self._to_ref(*p.split('_', 1))))
    ...
    ...     def _to_ref(self, pfx, name):
    ...         return URIRef(self._graph.store.namespace(pfx) + name)

It works as follows::

    >>> graph = Graph().parse(format='n3', data='''
    ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    ... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
    ...
    ... @base <http://example.org/> .
    ... </person/some1#self>
    ...     foaf:name "Some Body";
    ...     foaf:depiction </images/person/some1.jpg> .
    ... </images/person/some1.jpg> rdfs:comment "Just an image"@en .
    ... ''')

    >>> person = Item(graph, URIRef("http://example.org/person/some1#self"))

    >>> print(person.foaf_name[0])
    Some Body

The mechanism for wrapping references as resources cooperates with subclasses.
Therefore, accessing referenced resources automatically creates new ``Item``
objects::

    >>> isinstance(person.foaf_depiction[0], Item)
    True

    >>> print(person.foaf_depiction[0].rdfs_comment[0])
    Just an image

    )NodeBNodeURIRef)RDF)PathResourcec                   2   e Zd Zd Z ed       Z e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)dZd Zd Zd Zej2                  dddfdZd Zd Zd Zd)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*y)*r   c                      || _         || _        y N_graph_identifier)selfgraphsubjects      o/var/www/sten-cake5-migrate2.hellocrow.space/lexinfo-master/env/lib/python3.12/site-packages/rdflib/resource.py__init__zResource.__init__?  s    "    c                     | j                   S r   )r   r   s    r   <lambda>zResource.<lambda>C  s
    $++ r   c                     | j                   S r   r   r   s    r   r   zResource.<lambda>E  s    t'7'7 r   c                 x    t        t              t        | j                        z  t        | j                        z  S r   )hashr   r   r   r   s    r   __hash__zResource.__hash__G  s*    H~T[[ 11D9I9I4JJJr   c                     t        |t              xr4 | j                  |j                  k(  xr | j                  |j                  k(  S r   )
isinstancer   r   r   r   others     r   __eq__zResource.__eq__J  s?    uh' 6u||+6  E$5$55	
r   c                     | |k(   S r    r   s     r   __ne__zResource.__ne__Q  s    5=  r   c                 V    t        |t              r| j                  |j                  k  S y)NF)r   r   r   r   s     r   __lt__zResource.__lt__T  s&    eX&##e&7&777r   c                     | |k  xs | |k(   S r   r#   r   s     r   __gt__zResource.__gt__Z  s    5L1DEM22r   c                     | |k  xs | |k(  S r   r#   r   s     r   __le__zResource.__le__]  s    e|,tu},r   c                     | |k   S r   r#   r   s     r   __ge__zResource.__ge__`  s    %<r   c                 ,    t        | j                        S r   )strr   r   s    r   __unicode__zResource.__unicode__c  s    4##$$r   c                     t        |t              r|j                  }| j                  j	                  | j                  ||f       y r   )r   r   r   r   addr   pos      r   r1   zResource.addf  2    a"A))1a01r   Nc                     t        |t              r|j                  }| j                  j	                  | j                  ||f       y r   )r   r   r   r   remover2   s      r   r7   zResource.removel  s4    a"AD,,a34r   c                     t        |t              r|j                  }| j                  j	                  | j                  ||f       y r   )r   r   r   r   setr2   s      r   r9   zResource.setr  r5   r   c                 l    | j                  | j                  j                  || j                              S r   )
_resourcesr   subjectsr   r   	predicates     r   r<   zResource.subjectsx  s(    t{{33It?O?OPQQr   c                     t        |t              r|j                  }| j                  | j                  j                  | j                  |            S r   )r   r   r   r;   r   
predicates)r   r4   s     r   r@   zResource.predicates{  s;    a"At{{55d6F6FJKKr   c                 l    | j                  | j                  j                  | j                  |            S r   )r;   r   objectsr   r=   s     r   rB   zResource.objects  s(    t{{2243C3CYOPPr   c                 j    | j                  | j                  j                  | j                              S r   )_resource_pairsr   subject_predicatesr   r   s    r   rE   zResource.subject_predicates  s(    ##DKK$B$B4CSCS$TUUr   c                 j    | j                  | j                  j                  | j                              S r   )rD   r   subject_objectsr   r   s    r   rG   zResource.subject_objects  s(    ##DKK$?$?@P@P$QRRr   c                 j    | j                  | j                  j                  | j                              S r   )rD   r   predicate_objectsr   r   s    r   rI   zResource.predicate_objects  s(    ##DKK$A$A$BRBR$STTr   Tc           	          t        |t              r|j                  }| j                  | j                  j                  | j                  ||||            S r   )r   r   r   _castr   value)r   r3   r4   defaultanys        r   rL   zResource.value  sA    a"Azz$++++D,<,<aGSQRRr   c                 L    | j                   j                  | j                        S r   )r   labelr   r   s    r   rP   zResource.label      {{  !1!122r   c                 L    | j                   j                  | j                        S r   )r   commentr   r   s    r   rS   zResource.comment  s    {{""4#3#344r   c                 j    | j                  | j                  j                  | j                              S r   )r;   r   itemsr   r   s    r   rU   zResource.items  s&    t{{001A1ABCCr   c                 n    | j                  | j                  j                  | j                  ||            S r   )r;   r   transitive_objectsr   r   r>   remembers      r   rW   zResource.transitive_objects  s/    KK**4+;+;YQ
 	
r   c                 n    | j                  | j                  j                  || j                  |            S r   )r;   r   transitive_subjectsr   rX   s      r   r[   zResource.transitive_subjects  s/    KK++It7G7GR
 	
r   c                 j    | j                  | j                  j                  | j                              S r   )r;   r   seqr   r   s    r   r]   zResource.seq  s$    t{{t/?/?@AAr   c                 L    | j                   j                  | j                        S r   )r   qnamer   r   s    r   r_   zResource.qname  rQ   r   c              #   h   K   |D ])  \  }}| j                  |      | j                  |      f + y wr   rK   )r   pairss1s2s       r   rD   zResource._resource_pairs  s4      	1FB**R.$**R.00	1s   02c              #      K   |D ]:  \  }}}| j                  |      | j                  |      | j                  |      f < y wr   ra   )r   triplessr3   r4   s        r   _resource_tripleszResource._resource_triples  s@      	>GAq!**Q-A

1==	>s   AAc              #   @   K   |D ]  }| j                  |        y wr   ra   )r   nodesnodes      r   r;   zResource._resources  s$      	#D**T""	#s   c                 T    t        |t        t        f      r| j                  |      S |S r   )r   r   r   _new)r   rk   s     r   rK   zResource._cast  s#    dUFO,99T?"Kr   c                 p    | j                  | j                  j                  | j                  d d f            S r   )rh   r   rf   
identifierr   s    r   __iter__zResource.__iter__  s2    %%KK$ =>
 	
r   c                    t        |t              r|j                  rt        d      |j                  |j
                  }}t        |t              r|j                  }t        |t              r|j                  }||| j                         S || j                  |      S || j                  |      S | j                  ||f| j                  v S t        |t        t        f      r| j                  |      S t        d|dt        |      d      )NzSResources fix the subject for slicing, and can only be sliced by predicate/object. zTYou can only index a resource by a single rdflib term, a slice of rdflib terms, not z ())r   slicestep	TypeErrorstartstopr   r   rI   r@   rB   ro   r   r   r   type)r   itemr3   r4   s       r   __getitem__zResource.__getitem__  s    dE"yyi  ::tyyqA!X&MM!X&MMyQY--//q))||A&A.$++==tTl+<<%%d% r   c                 (    | j                  ||       y r   )r9   )r   ry   rL   s      r   __setitem__zResource.__setitem__  s    ur   c                 :     t        |       | j                  |      S r   )rx   r   )r   r   s     r   rm   zResource._new  s    tDz$++w//r   c                      d| j                   z  S )NzResource(%s)r   r   s    r   __str__zResource.__str__  s     0 000r   c                 <    d| j                   d| j                  dS )Nz	Resource(,rr   r   r   s    r   __repr__zResource.__repr__  s    $(KK1A1ABBr   r   )+__name__
__module____qualname__r   propertyr   ro   r   r!   r$   r&   r(   r*   r,   r/   r1   r7   r9   r<   r@   rB   rE   rG   rI   r   rL   rP   rS   rU   rW   r[   r]   r_   rD   rh   r;   rK   rp   rz   r|   rm   r   r   r#   r   r   r   r   >  s    # -.E78JK
!3- %252RLQVSU ii44 S35D



B31>#

601Cr   N)__doc__rdflib.termr   r   r   rdflib.namespacer   rdflib.pathsr   __all__objectr   r#   r   r   <module>r      s1   tl	 , +   ,jCv jCr   