summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorGunnar Aastrand Grimnes <gromgull@gmail.com>2013-05-07 22:29:21 +0200
committerGunnar Aastrand Grimnes <gromgull@gmail.com>2013-05-07 22:29:21 +0200
commit51ef22af04a6a260e09979d09ebdd4816e9542e4 (patch)
tree1874763e520b7ea0efc78637c28b85d855ee52bd /examples
parent67ace218e6921d443342b6574788f59b1155bbe5 (diff)
downloadrdflib-51ef22af04a6a260e09979d09ebdd4816e9542e4.tar.gz
and even more doc updates
Diffstat (limited to 'examples')
-rw-r--r--examples/__init__.py0
-rw-r--r--examples/conjunctive_graphs.py69
-rw-r--r--examples/custom_datatype.py43
-rw-r--r--examples/custom_eval.py35
-rw-r--r--examples/film.py25
-rw-r--r--examples/foafpaths.py46
-rw-r--r--examples/prepared_query.py30
-rw-r--r--examples/resource.py52
-rw-r--r--examples/simple_example.py81
-rw-r--r--examples/slice.py28
-rw-r--r--examples/sparql_query_example.py38
-rw-r--r--examples/sparql_update_example.py37
-rw-r--r--examples/swap_primer.py163
-rw-r--r--examples/transitive.py76
14 files changed, 429 insertions, 294 deletions
diff --git a/examples/__init__.py b/examples/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/examples/__init__.py
diff --git a/examples/conjunctive_graphs.py b/examples/conjunctive_graphs.py
index 216fa015..892582a0 100644
--- a/examples/conjunctive_graphs.py
+++ b/examples/conjunctive_graphs.py
@@ -1,37 +1,58 @@
-from rdflib import Namespace, BNode, Literal, URIRef
+"""
+
+An RDFLib ConjunctiveGraph is an (unamed) aggregation of all the named graphs
+within a Store. The :meth:`~rdflib.graph.ConjunctiveGraph.get_context`
+method can be used to get a particular named graph, or triples can be
+added to the default graph
+
+This example shows how to create some named graphs and work with the
+conjunction of all the graphs.
+
+"""
+
+from rdflib import Namespace, Literal, URIRef
from rdflib.graph import Graph, ConjunctiveGraph
from rdflib.plugins.memory import IOMemory
-ns = Namespace("http://love.com#")
+if __name__=='__main__':
+
+
+ ns = Namespace("http://love.com#")
+
+ mary = URIRef("http://love.com/lovers/mary#")
+ john = URIRef("http://love.com/lovers/john#")
+
+ cmary=URIRef("http://love.com/lovers/mary#")
+ cjohn=URIRef("http://love.com/lovers/john#")
-mary = URIRef("http://love.com/lovers/mary#")
-john = URIRef("http://love.com/lovers/john#")
+ store = IOMemory()
-cmary=URIRef("http://love.com/lovers/mary#")
-cjohn=URIRef("http://love.com/lovers/john#")
+ g = ConjunctiveGraph(store=store)
+ g.bind("love",ns)
-store = IOMemory()
+ gmary = Graph(store=store, identifier=cmary)
-g = ConjunctiveGraph(store=store)
-g.bind("love",ns)
+ gmary.add((mary, ns['hasName'], Literal("Mary")))
+ gmary.add((mary, ns['loves'], john))
-gmary = Graph(store=store, identifier=cmary)
+ gjohn = Graph(store=store, identifier=cjohn)
+ gjohn.add((john, ns['hasName'], Literal("John")))
-gmary.add((mary, ns['hasName'], Literal("Mary")))
-gmary.add((mary, ns['loves'], john))
+ #enumerate contexts
+ for c in g.contexts():
+ print("-- %s " % c)
-gjohn = Graph(store=store, identifier=cjohn)
-gjohn.add((john, ns['hasName'], Literal("John")))
+ #separate graphs
+ print(gjohn.serialize(format='n3'))
+ print("===================")
+ print(gmary.serialize(format='n3'))
+ print("===================")
-#enumerate contexts
-for c in g.contexts():
- print("-- %s " % c)
+ #full graph
+ print(g.serialize(format='n3'))
-#separate graphs
-print(gjohn.serialize(format='n3'))
-print("===================")
-print(gmary.serialize(format='n3'))
-print("===================")
+ # query the conjunction of all graphs
-#full graph
-print(g.serialize(format='n3'))
+ print 'Mary loves:'
+ for x in g[mary : ns.loves/ns.hasName]:
+ print x
diff --git a/examples/custom_datatype.py b/examples/custom_datatype.py
index b25b57d5..01aa5acb 100644
--- a/examples/custom_datatype.py
+++ b/examples/custom_datatype.py
@@ -1,7 +1,12 @@
"""
-rdflib.term.bind lets you register new mappings between literal
-datatypes and python objects
+RDFLib can map between data-typed literals and python objects.
+
+Mapping for integers, floats, dateTimes, etc. are already added, but
+you can also add your own.
+
+This example shows how :meth:`rdflib.term.bind` lets you register new
+mappings between literal datatypes and python objects
"""
@@ -9,31 +14,33 @@ datatypes and python objects
from rdflib import Graph, Literal, Namespace, XSD
from rdflib.term import bind
-# complex numbers are not registered by default
-# no custom constructor/serializer needed since
-# complex('(2+3j)') works fine
-bind(XSD.complexNumber, complex)
+if __name__=='__main__':
+
+ # complex numbers are not registered by default
+ # no custom constructor/serializer needed since
+ # complex('(2+3j)') works fine
+ bind(XSD.complexNumber, complex)
-ns=Namespace("urn:my:namespace:")
+ ns=Namespace("urn:my:namespace:")
-c=complex(2,3)
+ c=complex(2,3)
-l=Literal(c)
+ l=Literal(c)
-g=Graph()
-g.add((ns.mysubject, ns.myprop, l))
+ g=Graph()
+ g.add((ns.mysubject, ns.myprop, l))
-n3=g.serialize(format='n3')
+ n3=g.serialize(format='n3')
-# round-trip through n3
+ # round-trip through n3
-g2=Graph()
-g2.parse(data=n3, format='n3')
+ g2=Graph()
+ g2.parse(data=n3, format='n3')
-l2=list(g2)[0][2]
+ l2=list(g2)[0][2]
-print l2
+ print l2
-print l2.value == c # back to a python complex object
+ print l2.value == c # back to a python complex object
diff --git a/examples/custom_eval.py b/examples/custom_eval.py
index 0b82b6b4..89975168 100644
--- a/examples/custom_eval.py
+++ b/examples/custom_eval.py
@@ -3,12 +3,12 @@
This example shows how a custom evaluation function can be added to
handle certain SPARQL Algebra elements
-A custom function is added that adds subClassOf "inference" when
-asking for rdf:type triples.
+A custom function is added that adds ``rdfs:subClassOf`` "inference" when
+asking for ``rdf:type`` triples.
Here the custom eval function is added manually, normally you would use
setuptools and entry_points to do it:
-i.e. in your setup.py:
+i.e. in your setup.py::
entry_points = {
'rdf.plugins.sparqleval': [
@@ -18,14 +18,13 @@ i.e. in your setup.py:
"""
-import rdflib.plugins.sparql.paths
import rdflib
from rdflib.plugins.sparql.evaluate import evalBGP
from rdflib.namespace import FOAF
inferredSubClass = \
- rdflib.RDFS.subClassOf % '*' # any number of rdfs.subClassOf
+ rdflib.RDFS.subClassOf * '*' # any number of rdfs.subClassOf
def customEval(ctx, part):
@@ -50,18 +49,20 @@ def customEval(ctx, part):
raise NotImplementedError()
-# add function directly, normally we would use setuptools and entry_points
-rdflib.plugins.sparql.CUSTOM_EVALS['exampleEval'] = customEval
+if __name__=='__main__':
-g = rdflib.Graph()
-g.load("foaf.rdf")
+ # add function directly, normally we would use setuptools and entry_points
+ rdflib.plugins.sparql.CUSTOM_EVALS['exampleEval'] = customEval
-# Add the subClassStmt so that we can query for it!
-g.add((FOAF.Person,
- rdflib.RDFS.subClassOf,
- FOAF.Agent))
+ g = rdflib.Graph()
+ g.load("foaf.rdf")
-# Find all FOAF Agents
-for x in g.query(
- 'PREFIX foaf: <%s> SELECT * WHERE { ?s a foaf:Agent . }' % FOAF):
- print x
+ # Add the subClassStmt so that we can query for it!
+ g.add((FOAF.Person,
+ rdflib.RDFS.subClassOf,
+ FOAF.Agent))
+
+ # Find all FOAF Agents
+ for x in g.query(
+ 'PREFIX foaf: <%s> SELECT * WHERE { ?s a foaf:Agent . }' % FOAF):
+ print x
diff --git a/examples/film.py b/examples/film.py
index 74514190..832ba3be 100644
--- a/examples/film.py
+++ b/examples/film.py
@@ -1,5 +1,7 @@
#!/usr/bin/env python
-""" film.py: a simple tool to manage your movies review
+"""
+
+film.py: a simple tool to manage your movies review
Simon Rozet, http://atonie.org/
@@ :
@@ -21,12 +23,19 @@ Usage:
film.py http://www.imdb.com/title/tt0105236/
Review the movie "Reservoir Dogs"
"""
-import datetime, os, sys, re, time, imdb
+import datetime, os, sys, re, time
+
+try:
+ import imdb
+except ImportError:
+ imdb = None
+
from rdflib import BNode, ConjunctiveGraph, URIRef, Literal, Namespace, RDF
from rdflib.namespace import FOAF, DC
-#storefn = os.path.expanduser('~/movies.n3')
-storefn = '/home/simon/codes/film.dev/movies.n3'
+
+storefn = os.path.expanduser('~/movies.n3')
+#storefn = '/home/simon/codes/film.dev/movies.n3'
storeuri = 'file://'+storefn
title = 'Movies viewed by %s'
@@ -40,9 +49,9 @@ class Store:
self.graph = ConjunctiveGraph()
if os.path.exists(storefn):
self.graph.load(storeuri, format='n3')
- self.graph.bind('dc', 'http://purl.org/dc/elements/1.1/')
- self.graph.bind('foaf', 'http://xmlns.com/foaf/0.1/')
- self.graph.bind('imdb', 'http://www.csd.abdn.ac.uk/~ggrimnes/dev/imdb/IMDB#')
+ self.graph.bind('dc', DC)
+ self.graph.bind('foaf', FOAF)
+ self.graph.bind('imdb', IMDB)
self.graph.bind('rev', 'http://purl.org/stuff/rev#')
def save(self):
@@ -128,4 +137,6 @@ def main(argv=None):
help()
if __name__ == '__main__':
+ if not imdb:
+ raise Exception('This example requires the IMDB library! Install with "pip install imdbpy"')
main()
diff --git a/examples/foafpaths.py b/examples/foafpaths.py
index dd2f2f02..81179347 100644
--- a/examples/foafpaths.py
+++ b/examples/foafpaths.py
@@ -1,34 +1,44 @@
"""
-SPARQL 1.1 defines path operators
+SPARQL 1.1 defines path operators for combining/repeating predicates
+in triple-patterns.
We overload some python operators on URIRefs to allow creating path
operators directly in python.
-p1 / p2 => Path sequence
-p1 | p2 => Path alternative
-p1 * '*' => chain of 0 or more p's
-p1 * '+' => chain of 1 or more p's
-p1 * '?' => 0 or 1 p
-~p1 => p1 is inverted order (s p1 o) <=> (o ~p1 s)
--p1 => NOT p1, i.e. any property by p1
+============ =========================================
+Operator Path
+============ =========================================
+``p1 / p2`` Path sequence
+``p1 | p2`` Path alternative
+``p1 * '*'`` chain of 0 or more p's
+``p1 * '+'`` chain of 1 or more p's
+``p1 * '?'`` 0 or 1 p
+``~p1`` p1 inverted, i.e. (s p1 o) <=> (o ~p1 s)
+``-p1`` NOT p1, i.e. any property but p1
+============ =========================================
-these can then be used in property position for s,p,o triple queries
-for graph objects
-See the docs for rdflib.plugins.sparql.path for the details
+these can then be used in property position for ``s,p,o`` triple queries
+for any graph method.
+
+See the docs for :mod:`rdflib.paths` for the details.
+
+This example shows how to get the name of friends with a single query.
"""
-from rdflib import URIRef, Graph, Namespace
+from rdflib import URIRef, Graph
from rdflib.namespace import FOAF
-g = Graph()
-g.load("foaf.rdf")
+if __name__=='__main__':
+
+ g = Graph()
+ g.load("foaf.rdf")
-tim = URIRef("http://www.w3.org/People/Berners-Lee/card#i")
+ tim = URIRef("http://www.w3.org/People/Berners-Lee/card#i")
-print "Timbl knows:"
+ print "Timbl knows:"
-for o in g.objects(tim, FOAF.knows / FOAF.name):
- print o
+ for o in g.objects(tim, FOAF.knows / FOAF.name):
+ print o
diff --git a/examples/prepared_query.py b/examples/prepared_query.py
index 489ff6fc..f67c1b5e 100644
--- a/examples/prepared_query.py
+++ b/examples/prepared_query.py
@@ -1,16 +1,12 @@
"""
-Prepared Queries Example
-------------------------
-
-Queries be prepared (i.e parsed and translated to SPARQL algebra)
-by
-
-rdlfib.plugins.sparql.prepareQuery
+SPARQL Queries be prepared (i.e parsed and translated to SPARQL algebra)
+by the :meth:`rdflib.plugins.sparql.prepareQuery` method.
When executing, variables can be bound with the
-initBindings keyword parameter
+``initBindings`` keyword parameter
+
"""
@@ -18,14 +14,16 @@ import rdflib
from rdflib.plugins.sparql import prepareQuery
from rdflib.namespace import FOAF
-q = prepareQuery(
- 'SELECT ?s WHERE { ?person foaf:knows ?s .}',
- initNs = { "foaf": FOAF })
+if __name__=='__main__':
+
+ q = prepareQuery(
+ 'SELECT ?s WHERE { ?person foaf:knows ?s .}',
+ initNs = { "foaf": FOAF })
-g = rdflib.Graph()
-g.load("foaf.rdf")
+ g = rdflib.Graph()
+ g.load("foaf.rdf")
-tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i")
+ tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i")
-for row in g.query(q, initBindings={'person': tim}):
- print row
+ for row in g.query(q, initBindings={'person': tim}):
+ print row
diff --git a/examples/resource.py b/examples/resource.py
index 0f61c92a..4a738efd 100644
--- a/examples/resource.py
+++ b/examples/resource.py
@@ -1,6 +1,10 @@
"""
-RDFLib has a Resource class, for a resource-centric API
+RDFLib has a :class:`~rdflib.resource.Resource` class, for a resource-centric API.
+
+A resource acts like a URIRef with an associated graph, and allows
+quickly adding or querying for triples where this resource is the
+subject.
"""
@@ -8,38 +12,40 @@ RDFLib has a Resource class, for a resource-centric API
from rdflib import Graph, RDF, RDFS, Literal
from rdflib.namespace import FOAF
-g = Graph()
+if __name__=='__main__':
+
+ g = Graph()
-bob = g.resource('urn:bob')
+ bob = g.resource('urn:bob')
-bob.set(RDF.type, FOAF.Person) # .set replaces all other values
-bob.set(FOAF.name, Literal("Bob"))
+ bob.set(RDF.type, FOAF.Person) # .set replaces all other values
+ bob.set(FOAF.name, Literal("Bob"))
-bill = g.resource('urn:bill')
+ bill = g.resource('urn:bill')
-bill.add(RDF.type, FOAF.Person) # add adds to existing values
-bill.add(RDF.type, FOAF.Agent)
-bill.set(RDFS.label, Literal("Bill"))
+ bill.add(RDF.type, FOAF.Person) # add adds to existing values
+ bill.add(RDF.type, FOAF.Agent)
+ bill.set(RDFS.label, Literal("Bill"))
-bill.add(FOAF.knows, bob)
+ bill.add(FOAF.knows, bob)
-# Resources returned when querying are 'auto-boxed' as resources:
+ # Resources returned when querying are 'auto-boxed' as resources:
-print "Bill's friend: ", bill.value(FOAF.knows).value(FOAF.name)
+ print "Bill's friend: ", bill.value(FOAF.knows).value(FOAF.name)
-# slicing ([] syntax) can also be used:
+ # slicing ([] syntax) can also be used:
-print "Bill knows: ",
-for friend in bill[FOAF.knows]:
- print friend[FOAF.name].next(), " "
+ print "Bill knows: ",
+ for friend in bill[FOAF.knows]:
+ print friend[FOAF.name].next(), " "
-# or even quicker with paths:
-print "Bill knows: ",
-for friend in bill[FOAF.knows/FOAF.name]:
- print friend
+ # or even quicker with paths:
+ print "Bill knows: ",
+ for friend in bill[FOAF.knows/FOAF.name]:
+ print friend
-# setting single properties is also possible:
-bill[RDFS.label]=Literal("William")
+ # setting single properties is also possible:
+ bill[RDFS.label]=Literal("William")
-print g.serialize(format='n3')
+ print g.serialize(format='n3')
diff --git a/examples/simple_example.py b/examples/simple_example.py
index bdfb96e2..7b44ff79 100644
--- a/examples/simple_example.py
+++ b/examples/simple_example.py
@@ -1,58 +1,53 @@
-import logging
-
-# Optional: Configure how we want rdflib logger to log messages
-_logger = logging.getLogger("rdflib")
-_logger.setLevel(logging.DEBUG)
-_hdlr = logging.StreamHandler()
-_hdlr.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
-_logger.addHandler(_hdlr)
from rdflib import Graph, Literal, BNode, RDF
from rdflib.namespace import FOAF, DC
-store = Graph()
+if __name__=='__main__':
+
+ store = Graph()
-# Bind a few prefix, namespace pairs for pretty output
-store.bind("dc", DC)
-store.bind("foaf", FOAF)
+ # Bind a few prefix, namespace pairs for pretty output
+ store.bind("dc", DC)
+ store.bind("foaf", FOAF)
-# Create an identifier to use as the subject for Donna.
-donna = BNode()
+ # Create an identifier to use as the subject for Donna.
+ donna = BNode()
-# Add triples using store's add method.
-store.add((donna, RDF.type, FOAF.Person))
-store.add((donna, FOAF.nick, Literal("donna", lang="foo")))
-store.add((donna, FOAF.name, Literal("Donna Fales")))
+ # Add triples using store's add method.
+ store.add((donna, RDF.type, FOAF.Person))
+ store.add((donna, FOAF.nick, Literal("donna", lang="foo")))
+ store.add((donna, FOAF.name, Literal("Donna Fales")))
-# Iterate over triples in store and print them out.
-print "--- printing raw triples ---"
-for s, p, o in store:
- print s, p, o
+ # Iterate over triples in store and print them out.
+ print "--- printing raw triples ---"
+ for s, p, o in store:
+ print s, p, o
-# For each foaf:Person in the store print out its mbox property.
-print "--- printing mboxes ---"
-for person in store.subjects(RDF.type, FOAF["Person"]):
- for mbox in store.objects(person, FOAF["mbox"]):
- print mbox
+ # For each foaf:Person in the store print out its mbox property.
+ print "--- printing mboxes ---"
+ for person in store.subjects(RDF.type, FOAF["Person"]):
+ for mbox in store.objects(person, FOAF["mbox"]):
+ print mbox
-# Serialize the store as RDF/XML to the file foaf.rdf.
-store.serialize("foaf.rdf", format="pretty-xml", max_depth=3)
+ # Serialize the store as RDF/XML to the file donna_foaf.rdf.
+ store.serialize("donna_foaf.rdf", format="pretty-xml", max_depth=3)
-# Let's show off the serializers
+ # Let's show off the serializers
-print "RDF Serializations:"
+ print "RDF Serializations:"
-# Serialize as XML
-print "--- start: rdf-xml ---"
-print store.serialize(format="pretty-xml")
-print "--- end: rdf-xml ---\n"
+ # Serialize as XML
+ print "--- start: rdf-xml ---"
+ print store.serialize(format="pretty-xml")
+ print "--- end: rdf-xml ---\n"
-# Serialize as Turtle
-print "--- start: turtle ---"
-print store.serialize(format="turtle")
-print "--- end: turtle ---\n"
+ # Serialize as Turtle
+ print "--- start: turtle ---"
+ print store.serialize(format="turtle")
+ print "--- end: turtle ---\n"
-# Serialize as NTriples
-print "--- start: ntriples ---"
-print store.serialize(format="nt")
-print "--- end: ntriples ---\n"
+ # Serialize as NTriples
+ print "--- start: ntriples ---"
+ print store.serialize(format="nt")
+ print "--- end: ntriples ---\n"
+
diff --git a/examples/slice.py b/examples/slice.py
index 390ba481..2e4e2d8b 100644
--- a/examples/slice.py
+++ b/examples/slice.py
@@ -4,23 +4,27 @@ RDFLib Graphs (and Resources) can be "sliced" with [] syntax
This is a short-hand for iterating over triples
-Combined with SPARQL paths (see foafpaths.py) - quite complex queries
-can be realised
+Combined with SPARQL paths (see ``foafpaths.py``) - quite complex queries
+can be realised.
+
+See :meth:`rdflib.graph.Graph.__getitem__` for details
"""
from rdflib import Graph, RDF
from rdflib.namespace import FOAF
-graph = Graph()
+if __name__=='__main__':
+
+ graph = Graph()
+
+ graph.load("foaf.rdf")
+
+ for person in graph[: RDF.type : FOAF.Person]:
-graph.load("foaf.rdf")
+ friends = list(graph[person:FOAF.knows * '+'/FOAF.name])
+ if friends:
+ print "%s's circle of friends:"%graph.value(person, FOAF.name)
+ for name in friends:
+ print name
-for person in graph[: RDF.type : FOAF.Person]:
-
- friends = list(graph[person:FOAF.knows * '+'/FOAF.name])
- if friends:
- print "%s's circle of friends:"%graph.value(person, FOAF.name)
- for name in friends:
- print name
-
diff --git a/examples/sparql_query_example.py b/examples/sparql_query_example.py
index 293c4354..90417b5e 100644
--- a/examples/sparql_query_example.py
+++ b/examples/sparql_query_example.py
@@ -1,32 +1,34 @@
"""
-Query using graph.query
+SPARQL Query using :meth:`rdflib.graph.Graph.query`
-Result is iterable over the result rows
+The method returns a :class:`~rdflib.query.Result`, iterating over
+this yields :class:`~rdflib.query.ResultRow` objects
-The variable bindings can be access
-as attributes of the row objects
-For variable names that are not valid python identifiers,
-dict access (i.e. with row[var] / __getitem__) is also possible.
+The variable bindings can be access as attributes of the row objects
+For variable names that are not valid python identifiers, dict access
+(i.e. with ``row[var] / __getitem__``) is also possible.
-result.vars contains the variables
+:attr:`~rdflib.query.ResultRow.vars` contains the variables
"""
import rdflib
-g = rdflib.Graph()
-g.load("foaf.rdf")
-
-# the QueryProcessor knows the FOAF prefix from the graph
-# which in turn knows it from reading the RDF/XML file
-for row in g.query(
- 'select ?s where { [] foaf:knows ?s .}'):
- print row.s
- # or row["s"]
- # or row[rdflib.Variable("s")]
-
+if __name__=='__main__':
+
+ g = rdflib.Graph()
+ g.load("foaf.rdf")
+
+ # the QueryProcessor knows the FOAF prefix from the graph
+ # which in turn knows it from reading the RDF/XML file
+ for row in g.query(
+ 'select ?s where { [] foaf:knows ?s .}'):
+ print row.s
+ # or row["s"]
+ # or row[rdflib.Variable("s")]
+
diff --git a/examples/sparql_update_example.py b/examples/sparql_update_example.py
index cb832821..ece18ed7 100644
--- a/examples/sparql_update_example.py
+++ b/examples/sparql_update_example.py
@@ -1,25 +1,26 @@
"""
-Process SPARQL Update
+SPARQL Update statements can be applied with :meth:`rdflib.graph.Graph.update`
"""
import rdflib
-from rdflib.plugins.sparql import processUpdate
-
-g = rdflib.Graph()
-g.load("foaf.rdf")
-
-processUpdate(g, '''
-PREFIX foaf: <http://xmlns.com/foaf/0.1/>
-PREFIX dbpedia: <http://dbpedia.org/resource/>
-INSERT
- { ?s a dbpedia:Human . }
-WHERE
- { ?s a foaf:Person . }
-''')
-
-for x in g.subjects(
- rdflib.RDF.type, rdflib.URIRef('http://dbpedia.org/resource/Human')):
- print x
+
+if __name__=='__main__':
+
+ g = rdflib.Graph()
+ g.load("foaf.rdf")
+
+ g.update('''
+ PREFIX foaf: <http://xmlns.com/foaf/0.1/>
+ PREFIX dbpedia: <http://dbpedia.org/resource/>
+ INSERT
+ { ?s a dbpedia:Human . }
+ WHERE
+ { ?s a foaf:Person . }
+ ''')
+
+ for x in g.subjects(
+ rdflib.RDF.type, rdflib.URIRef('http://dbpedia.org/resource/Human')):
+ print x
diff --git a/examples/swap_primer.py b/examples/swap_primer.py
index 9780e425..aee57185 100644
--- a/examples/swap_primer.py
+++ b/examples/swap_primer.py
@@ -1,136 +1,139 @@
-# http://www.w3.org/2000/10/swap/Primer
+"""
-# This is a simple primer using some of the
-# example stuff in the above Primer on N3
-# get RDFLib at http://rdflib.net/
+This is a simple primer using some of the
+example stuff in the Primer on N3:
+http://www.w3.org/2000/10/swap/Primer
+
+"""
# Load up RDFLib
from rdflib import ConjunctiveGraph, Namespace, Literal
-from rdflib.parser import StringInputSource
+from rdflib.namespace import OWL, DC
+
+if __name__=='__main__':
-# Firstly, it doesn't have to be so complex.
-# Here we create a "Graph" of our work.
-# Think of it as a blank piece of graph paper!
+ # Firstly, it doesn't have to be so complex.
+ # Here we create a "Graph" of our work.
+ # Think of it as a blank piece of graph paper!
-primer = ConjunctiveGraph()
-myNS = Namespace('#')
+ primer = ConjunctiveGraph()
+ myNS = Namespace('#')
-primer.add((myNS.pat, myNS.knows, myNS.jo))
-# or:
-primer.add((myNS['pat'], myNS['age'], Literal(24)))
+ primer.add((myNS.pat, myNS.knows, myNS.jo))
+ # or:
+ primer.add((myNS['pat'], myNS['age'], Literal(24)))
-# Now, with just that, lets see how the system
-# recorded *way* too many details about what
-# you just asserted as fact.
-#
+ # Now, with just that, lets see how the system
+ # recorded *way* too many details about what
+ # you just asserted as fact.
+ #
-from pprint import pprint
-pprint(list(primer))
+ from pprint import pprint
+ pprint(list(primer))
-# just think .whatever((s, p, o))
-# here we report on what we know
+ # just think .whatever((s, p, o))
+ # here we report on what we know
-pprint(list(primer.subjects()))
-pprint(list(primer.predicates()))
-pprint(list(primer.objects()))
+ pprint(list(primer.subjects()))
+ pprint(list(primer.predicates()))
+ pprint(list(primer.objects()))
-# and other things that make sense
+ # and other things that make sense
-# what do we know about pat?
-pprint(list(primer.predicate_objects(myNS.pat)))
+ # what do we know about pat?
+ pprint(list(primer.predicate_objects(myNS.pat)))
-# who is what age?
-pprint(list(primer.subject_objects(myNS.age)))
+ # who is what age?
+ pprint(list(primer.subject_objects(myNS.age)))
-# Okay, so lets now work with a bigger
-# dataset from the example, and start
-# with a fresh new graph.
+ # Okay, so lets now work with a bigger
+ # dataset from the example, and start
+ # with a fresh new graph.
-primer = ConjunctiveGraph()
+ primer = ConjunctiveGraph()
-# Lets start with a verbatim string straight from the primer text:
+ # Lets start with a verbatim string straight from the primer text:
-mySource = """
+ mySource = """
-@prefix : <http://www.w3.org/2000/10/swap/Primer#>.
-@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 dc: <http://purl.org/dc/elements/1.1/> .
-@prefix foo: <http://www.w3.org/2000/10/swap/Primer#>.
-@prefix swap: <http://www.w3.org/2000/10/swap/>.
+ @prefix : <http://www.w3.org/2000/10/swap/Primer#>.
+ @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 dc: <http://purl.org/dc/elements/1.1/> .
+ @prefix foo: <http://www.w3.org/2000/10/swap/Primer#>.
+ @prefix swap: <http://www.w3.org/2000/10/swap/>.
-<> dc:title
- "Primer - Getting into the Semantic Web and RDF using N3".
+ <> dc:title
+ "Primer - Getting into the Semantic Web and RDF using N3".
-<#pat> <#knows> <#jo> .
-<#pat> <#age> 24 .
-<#al> is <#child> of <#pat> .
+ <#pat> <#knows> <#jo> .
+ <#pat> <#age> 24 .
+ <#al> is <#child> of <#pat> .
-<#pat> <#child> <#al>, <#chaz>, <#mo> ;
- <#age> 24 ;
- <#eyecolor> "blue" .
+ <#pat> <#child> <#al>, <#chaz>, <#mo> ;
+ <#age> 24 ;
+ <#eyecolor> "blue" .
-:Person a rdfs:Class.
+ :Person a rdfs:Class.
-:Pat a :Person.
+ :Pat a :Person.
-:Woman a rdfs:Class; rdfs:subClassOf :Person .
+ :Woman a rdfs:Class; rdfs:subClassOf :Person .
-:sister a rdf:Property.
+ :sister a rdf:Property.
-:sister rdfs:domain :Person;
- rdfs:range :Woman.
+ :sister rdfs:domain :Person;
+ rdfs:range :Woman.
-:Woman = foo:FemaleAdult .
-:Title a rdf:Property; = dc:title .
+ :Woman = foo:FemaleAdult .
+ :Title a rdf:Property; = dc:title .
-""" # --- End of primer code
+ """ # --- End of primer code
-# To make this go easier to spit back out...
-# technically, we already created a namespace
-# with the object init (and it added some namespaces as well)
-# By default, your main namespace is the URI of your
-# current working directory, so lets make that simpler:
+ # To make this go easier to spit back out...
+ # technically, we already created a namespace
+ # with the object init (and it added some namespaces as well)
+ # By default, your main namespace is the URI of your
+ # current working directory, so lets make that simpler:
-myNS = Namespace('http://www.w3.org/2000/10/swap/Primer#')
-primer.bind('', myNS)
-primer.bind('owl', 'http://www.w3.org/2002/07/owl#')
-primer.bind('dc', 'http://purl.org/dc/elements/1.1/')
-primer.bind('swap', 'http://www.w3.org/2000/10/swap/')
-sourceCode = StringInputSource(mySource, myNS)
+ myNS = Namespace('http://www.w3.org/2000/10/swap/Primer#')
+ primer.bind('', myNS)
+ primer.bind('owl', OWL)
+ primer.bind('dc', DC)
+ primer.bind('swap', 'http://www.w3.org/2000/10/swap/')
-# Lets load it up!
+ # Lets load it up!
-primer.parse(sourceCode, format='n3')
+ primer.parse(data=mySource, format='n3')
-# Now you can query, either directly straight into a list:
+ # Now you can query, either directly straight into a list:
-[(x, y, z) for x, y, z in primer]
+ [(x, y, z) for x, y, z in primer]
-# or spit it back out (mostly) the way we created it:
+ # or spit it back out (mostly) the way we created it:
-print primer.serialize(format='n3')
+ print primer.serialize(format='n3')
-# for more insight into things already done, lets see the namespaces
+ # for more insight into things already done, lets see the namespaces
-list(primer.namespaces())
+ list(primer.namespaces())
-# lets ask something about the data
+ # lets ask something about the data
-list(primer.objects(myNS.pat, myNS.child))
+ list(primer.objects(myNS.pat, myNS.child))
diff --git a/examples/transitive.py b/examples/transitive.py
new file mode 100644
index 00000000..dfa503be
--- /dev/null
+++ b/examples/transitive.py
@@ -0,0 +1,76 @@
+"""
+
+An example illustrating how to use the
+:meth:`~rdflib.graph.Graph.transitive_subjects` and
+:meth:`~rdflib.graph.Graph.transitive_objects` graph methods
+
+Formal definition
+^^^^^^^^^^^^^^^^^^
+
+The :meth:`~rdflib.graph.Graph.transitive_objects` method finds all
+nodes such that there is a path from subject to one of those nodes
+using only the predicate property in the triples. The
+:meth:`~rdflib.graph.Graph.transitive_subjects` method is similar; it
+finds all nodes such that there is a path from the node to the object
+using only the predicate property.
+
+Informal description, with an example
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In brief, :meth:`~rdflib.graph.Graph.transitive_objects` walks forward
+in a graph using a particular property, and
+:meth:`~rdflib.graph.Graph.transitive_subjects` walks backward. A good
+example uses a property ``ex:parent``, the semantics of which are
+biological parentage. The
+:meth:`~rdflib.graph.Graph.transitive_objects` method would get all
+the ancestors of a particular person (all nodes such that there is a
+parent path between the person and the object). The
+:meth:`~rdflib.graph.Graph.transitive_subjects` method would get all
+the descendants of a particular person (all nodes such that there is a
+parent path between the node and the person). So, say that your URI is
+``ex:person``.
+
+This example would get all of your (known) ancestors, and then get all
+the (known) descendants of your maternal grandmother.
+
+.. warning:: The :meth:`transitive_objects` method has the start node
+ as the *first* argument, but the :meth:`transitive_subjects`
+ method has the start node as the *second* argument.
+
+User-defined transitive closures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The method :meth:`~rdflib.graph.Graph.transitiveClosure` returns
+transtive closures of user-defined functions.
+
+"""
+
+if __name__=='__main__':
+ from rdflib import ConjunctiveGraph, URIRef
+
+ person = URIRef('ex:person')
+ dad = URIRef('ex:d')
+ mom = URIRef('ex:m')
+ momOfDad = URIRef('ex:gm0')
+ momOfMom = URIRef('ex:gm1')
+ dadOfDad = URIRef('ex:gf0')
+ dadOfMom = URIRef('ex:gf1')
+
+ parent = URIRef('ex:parent')
+
+ g = ConjunctiveGraph()
+ g.add((person, parent, dad))
+ g.add((person, parent, mom))
+ g.add((dad, parent, momOfDad))
+ g.add((dad, parent, dadOfDad))
+ g.add((mom, parent, momOfMom))
+ g.add((mom, parent, dadOfMom))
+
+ print "Parents, forward from `ex:person`:"
+ for i in g.transitive_objects(person, parent):
+ print i
+
+ print "Parents, *backward* from `ex:gm1`:"
+ for i in g.transitive_subjects(parent, momOfMom):
+ print i
+