src/rdflib/resource.py
1"""
2The [`Resource`][rdflib.resource.Resource] class wraps a
3[`Graph`][rdflib.graph.Graph]
4and a resource reference (i.e. a [`URIRef`][rdflib.term.URIRef] or
5[`BNode`][rdflib.term.BNode]) to support a resource-oriented way of
6working with a graph.
7
8It contains methods directly corresponding to those methods of the Graph
9interface that relate to reading and writing data. The difference is that a
10Resource also binds a resource identifier, making it possible to work without
11tracking both the graph and a current subject. This makes for a "resource
12oriented" style, as compared to the triple orientation of the Graph API.
13
14Resulting generators are also wrapped so that any resource reference values
15([`URIRef`][rdflib.term.URIRef] and [`BNode`][rdflib.term.BNode]) are in turn
16wrapped as Resources. (Note that this behaviour differs from the corresponding
17methods in [`Graph`][rdflib.graph.Graph], where no such conversion takes place.)
18
19
20## Basic Usage Scenario
21
22Start by importing things we need and define some namespaces:
23
24```python
25>>> from rdflib import *
26>>> FOAF = Namespace("http://xmlns.com/foaf/0.1/")
27>>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#")
28
29```
30
31Load some RDF data:
32
33```python
34>>> graph = Graph().parse(format='n3', data='''
35... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
36... @prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
37... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
38... @prefix cv: <http://purl.org/captsolo/resume-rdf/0.2/cv#> .
39...
40... @base <http://example.org/> .
41...
42... </person/some1#self> a foaf:Person;
43... rdfs:comment "Just a Python & RDF hacker."@en;
44... foaf:depiction </images/person/some1.jpg>;
45... foaf:homepage <http://example.net/>;
46... foaf:name "Some Body" .
47...
48... </images/person/some1.jpg> a foaf:Image;
49... rdfs:label "some 1"@en;
50... rdfs:comment "Just an image"@en;
51... foaf:thumbnail </images/person/some1-thumb.jpg> .
52...
53... </images/person/some1-thumb.jpg> a foaf:Image .
54...
55... [] a cv:CV;
56... cv:aboutPerson </person/some1#self>;
57... cv:hasWorkHistory [ cv:employedIn </#company>;
58... cv:startDate "2009-09-04"^^xsd:date ] .
59... ''')
60
61```
62
63Create a Resource:
64
65```python
66>>> person = Resource(
67... graph, URIRef("http://example.org/person/some1#self"))
68
69```
70
71Retrieve some basic facts:
72
73```python
74>>> person.identifier
75rdflib.term.URIRef('http://example.org/person/some1#self')
76
77>>> person.value(FOAF.name)
78rdflib.term.Literal('Some Body')
79
80>>> person.value(RDFS.comment)
81rdflib.term.Literal('Just a Python & RDF hacker.', lang='en')
82
83```
84
85Resources can be sliced (like graphs, but the subject is fixed):
86
87```python
88>>> for name in person[FOAF.name]:
89... print(name)
90Some Body
91>>> person[FOAF.name : Literal("Some Body")]
92True
93
94```
95
96Resources as unicode are represented by their identifiers as unicode:
97
98```python
99>>> %(unicode)s(person) #doctest: +SKIP
100'Resource(http://example.org/person/some1#self'
101
102```
103
104Resource references are also Resources, so you can easily get e.g. a qname
105for the type of a resource, like:
106
107```python
108>>> person.value(RDF.type).qname()
109'foaf:Person'
110
111```
112
113Or for the predicates of a resource:
114
115```python
116>>> sorted(
117... p.qname() for p in person.predicates()
118... ) #doctest: +NORMALIZE_WHITESPACE +SKIP
119['foaf:depiction', 'foaf:homepage',
120 'foaf:name', 'rdf:type', 'rdfs:comment']
121
122```
123
124Follow relations and get more data from their Resources as well:
125
126```python
127>>> for pic in person.objects(FOAF.depiction):
128... print(pic.identifier)
129... print(pic.value(RDF.type).qname())
130... print(pic.value(FOAF.thumbnail).identifier)
131http://example.org/images/person/some1.jpg
132foaf:Image
133http://example.org/images/person/some1-thumb.jpg
134
135```
136
137```python
138>>> for cv in person.subjects(CV.aboutPerson):
139... work = list(cv.objects(CV.hasWorkHistory))[0]
140... print(work.value(CV.employedIn).identifier)
141... print(work.value(CV.startDate))
142http://example.org/#company
1432009-09-04
144
145```
146
147It's just as easy to work with the predicates of a resource:
148
149```python
150>>> for s, p in person.subject_predicates():
151... print(s.value(RDF.type).qname())
152... print(p.qname())
153... for s, o in p.subject_objects():
154... print(s.value(RDF.type).qname())
155... print(o.value(RDF.type).qname())
156cv:CV
157cv:aboutPerson
158cv:CV
159foaf:Person
160
161```
162
163This is useful for e.g. inspection:
164
165```python
166>>> thumb_ref = URIRef("http://example.org/images/person/some1-thumb.jpg")
167>>> thumb = Resource(graph, thumb_ref)
168>>> for p, o in thumb.predicate_objects():
169... print(p.qname())
170... print(o.qname())
171rdf:type
172foaf:Image
173
174```
175
176## Schema Example
177
178With this artificial schema data:
179
180```python
181>>> graph = Graph().parse(format='n3', data='''
182... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
183... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
184... @prefix owl: <http://www.w3.org/2002/07/owl#> .
185... @prefix v: <http://example.org/def/v#> .
186...
187... v:Artifact a owl:Class .
188...
189... v:Document a owl:Class;
190... rdfs:subClassOf v:Artifact .
191...
192... v:Paper a owl:Class;
193... rdfs:subClassOf v:Document .
194...
195... v:Choice owl:oneOf (v:One v:Other) .
196...
197... v:Stuff a rdf:Seq; rdf:_1 v:One; rdf:_2 v:Other .
198...
199... ''')
200
201```
202
203From this class:
204
205```python
206>>> artifact = Resource(graph, URIRef("http://example.org/def/v#Artifact"))
207
208```
209
210we can get at subclasses:
211
212```python
213>>> subclasses = list(artifact.transitive_subjects(RDFS.subClassOf))
214>>> [c.qname() for c in subclasses]
215['v:Artifact', 'v:Document', 'v:Paper']
216
217```
218
219and superclasses from the last subclass:
220
221```python
222>>> [c.qname() for c in subclasses[-1].transitive_objects(RDFS.subClassOf)]
223['v:Paper', 'v:Document', 'v:Artifact']
224
225```
226
227Get items from the Choice:
228
229```python
230>>> choice = Resource(graph, URIRef("http://example.org/def/v#Choice"))
231>>> [it.qname() for it in choice.value(OWL.oneOf).items()]
232['v:One', 'v:Other']
233
234```
235
236On add, other resources are auto-unboxed:
237
238```python
239>>> paper = Resource(graph, URIRef("http://example.org/def/v#Paper"))
240>>> paper.add(RDFS.subClassOf, artifact)
241>>> artifact in paper.objects(RDFS.subClassOf) # checks Resource instance
242True
243>>> (paper._identifier, RDFS.subClassOf, artifact._identifier) in graph
244True
245
246```
247
248## Technical Details
249
250Comparison is based on graph and identifier:
251
252```python
253>>> g1 = Graph()
254>>> t1 = Resource(g1, URIRef("http://example.org/thing"))
255>>> t2 = Resource(g1, URIRef("http://example.org/thing"))
256>>> t3 = Resource(g1, URIRef("http://example.org/other"))
257>>> t4 = Resource(Graph(), URIRef("http://example.org/other"))
258
259>>> t1 is t2
260False
261
262>>> t1 == t2
263True
264>>> t1 != t2
265False
266
267>>> t1 == t3
268False
269>>> t1 != t3
270True
271
272>>> t3 != t4
273True
274
275>>> t3 < t1 and t1 > t3
276True
277>>> t1 >= t1 and t1 >= t3
278True
279>>> t1 <= t1 and t3 <= t1
280True
281
282>>> t1 < t1 or t1 < t3 or t3 > t1 or t3 > t3
283False
284
285```
286
287Hash is computed from graph and identifier:
288
289```python
290>>> g1 = Graph()
291>>> t1 = Resource(g1, URIRef("http://example.org/thing"))
292
293>>> hash(t1) == hash(Resource(g1, URIRef("http://example.org/thing")))
294True
295
296>>> hash(t1) == hash(Resource(Graph(), t1.identifier))
297False
298>>> hash(t1) == hash(Resource(Graph(), URIRef("http://example.org/thing")))
299False
300
301```
302
303The Resource class is suitable as a base class for mapper toolkits. For
304example, consider this utility for accessing RDF properties via qname-like
305attributes:
306
307```python
308>>> class Item(Resource):
309...
310... def __getattr__(self, p):
311... return list(self.objects(self._to_ref(*p.split('_', 1))))
312...
313... def _to_ref(self, pfx, name):
314... return URIRef(self._graph.store.namespace(pfx) + name)
315
316```
317
318It works as follows:
319
320```python
321>>> graph = Graph().parse(format='n3', data='''
322... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
323... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
324...
325... @base <http://example.org/> .
326... </person/some1#self>
327... foaf:name "Some Body";
328... foaf:depiction </images/person/some1.jpg> .
329... </images/person/some1.jpg> rdfs:comment "Just an image"@en .
330... ''')
331
332>>> person = Item(graph, URIRef("http://example.org/person/some1#self"))
333
334>>> print(person.foaf_name[0])
335Some Body
336
337```
338
339The mechanism for wrapping references as resources cooperates with subclasses.
340Therefore, accessing referenced resources automatically creates new `Item`
341objects:
342
343```python
344>>> isinstance(person.foaf_depiction[0], Item)
345True
346
347>>> print(person.foaf_depiction[0].rdfs_comment[0])
348Just an image
349
350```
351"""
352
353from rdflib.namespace import RDF
354from rdflib.paths import Path
355from rdflib.term import BNode, Node, URIRef
356
357__all__ = ["Resource"]
358
359
360class Resource:
361 """A Resource is a wrapper for a graph and a resource identifier."""
362
363 def __init__(self, graph, subject):
364 self._graph = graph
365 self._identifier = subject
366
367 @property
368 def graph(self):
369 return self._graph
370
371 @property
372 def identifier(self):
373 return self._identifier
374
375 def __hash__(self):
376 return hash(Resource) ^ hash(self._graph) ^ hash(self._identifier)
377
378 def __eq__(self, other):
379 return (
380 isinstance(other, Resource)
381 and self._graph == other._graph
382 and self._identifier == other._identifier
383 )
384
385 def __ne__(self, other):
386 return not self == other
387
388 def __lt__(self, other):
389 if isinstance(other, Resource):
390 return self._identifier < other._identifier
391 else:
392 return False
393
394 def __gt__(self, other):
395 return not (self < other or self == other)
396
397 def __le__(self, other):
398 return self < other or self == other
399
400 def __ge__(self, other):
401 return not self < other
402
403 def __unicode__(self):
404 return str(self._identifier)
405
406 def add(self, p, o):
407 if isinstance(o, Resource):
408 o = o._identifier
409
410 self._graph.add((self._identifier, p, o))
411
412 def remove(self, p, o=None):
413 if isinstance(o, Resource):
414 o = o._identifier
415
416 self._graph.remove((self._identifier, p, o))
417
418 def set(self, p, o):
419 if isinstance(o, Resource):
420 o = o._identifier
421
422 self._graph.set((self._identifier, p, o))
423
424 def subjects(self, predicate=None): # rev
425 return self._resources(self._graph.subjects(predicate, self._identifier))
426
427 def predicates(self, o=None):
428 if isinstance(o, Resource):
429 o = o._identifier
430
431 return self._resources(self._graph.predicates(self._identifier, o))
432
433 def objects(self, predicate=None):
434 return self._resources(self._graph.objects(self._identifier, predicate))
435
436 def subject_predicates(self):
437 return self._resource_pairs(self._graph.subject_predicates(self._identifier))
438
439 def subject_objects(self):
440 return self._resource_pairs(self._graph.subject_objects(self._identifier))
441
442 def predicate_objects(self):
443 return self._resource_pairs(self._graph.predicate_objects(self._identifier))
444
445 def value(self, p=RDF.value, o=None, default=None, any=True):
446 if isinstance(o, Resource):
447 o = o._identifier
448
449 return self._cast(self._graph.value(self._identifier, p, o, default, any))
450
451 def items(self):
452 return self._resources(self._graph.items(self._identifier))
453
454 def transitive_objects(self, predicate, remember=None):
455 return self._resources(
456 self._graph.transitive_objects(self._identifier, predicate, remember)
457 )
458
459 def transitive_subjects(self, predicate, remember=None):
460 return self._resources(
461 self._graph.transitive_subjects(predicate, self._identifier, remember)
462 )
463
464 def qname(self):
465 return self._graph.qname(self._identifier)
466
467 def _resource_pairs(self, pairs):
468 for s1, s2 in pairs:
469 yield self._cast(s1), self._cast(s2)
470
471 def _resource_triples(self, triples):
472 for s, p, o in triples:
473 yield self._cast(s), self._cast(p), self._cast(o)
474
475 def _resources(self, nodes):
476 for node in nodes:
477 yield self._cast(node)
478
479 def _cast(self, node):
480 if isinstance(node, (BNode, URIRef)):
481 return self._new(node)
482 else:
483 return node
484
485 def __iter__(self):
486 return self._resource_triples(
487 self._graph.triples((self.identifier, None, None))
488 )
489
490 def __getitem__(self, item):
491 if isinstance(item, slice):
492 if item.step:
493 raise TypeError(
494 "Resources fix the subject for slicing, and can only be sliced by predicate/object. "
495 )
496 p, o = item.start, item.stop
497 if isinstance(p, Resource):
498 p = p._identifier
499 if isinstance(o, Resource):
500 o = o._identifier
501 if p is None and o is None:
502 return self.predicate_objects()
503 elif p is None:
504 return self.predicates(o)
505 elif o is None:
506 return self.objects(p)
507 else:
508 return (self.identifier, p, o) in self._graph
509 elif isinstance(item, (Node, Path)):
510 return self.objects(item)
511 else:
512 raise TypeError(
513 "You can only index a resource by a single rdflib term, a slice of rdflib terms, not %s (%s)"
514 % (item, type(item))
515 )
516
517 def __setitem__(self, item, value):
518 self.set(item, value)
519
520 def _new(self, subject):
521 return type(self)(self._graph, subject)
522
523 def __str__(self):
524 return "Resource(%s)" % self._identifier
525
526 def __repr__(self):
527 return "Resource(%s,%s)" % (self._graph, self._identifier)