diff --git a/rdflib/namespace.py b/rdflib/namespace.py index b3eddaa62..084646c2d 100644 --- a/rdflib/namespace.py +++ b/rdflib/namespace.py @@ -144,6 +144,20 @@ def __repr__(self): return f"Namespace({self!r})" def __contains__(self, ref): + """Allows to check if a URI is within (starts with) this Namespace. + + >>> from rdflib import URIRef + >>> namespace = Namespace('http://example.org/') + >>> uri = URIRef('http://example.org/foo') + >>> uri in namespace + True + >>> person_class = namespace['Person'] + >>> person_class in namespace + True + >>> obj = URIRef('http://not.example.org/bar') + >>> obj in namespace + False + """ return ref.startswith(self) # test namespace membership with "ref in ns" syntax diff --git a/test/test_namespace.py b/test/test_namespace.py index a36376f94..59ff0ecec 100644 --- a/test/test_namespace.py +++ b/test/test_namespace.py @@ -1,10 +1,21 @@ import unittest from rdflib.graph import Graph -from rdflib.namespace import Namespace, FOAF, RDF, RDFS, SH +from rdflib.namespace import Namespace, FOAF, RDF, RDFS, SH, DCTERMS from rdflib.term import URIRef +class NamespaceTest(unittest.TestCase): + def test_dcterms_title(self): + self.assertEqual(DCTERMS.title, URIRef(DCTERMS + 'title')) + + def test_iri(self): + prefix = u'http://jörn.loves.encoding.problems/' + ns = Namespace(prefix) + self.assertEqual(ns, str(prefix)) + self.assert_(ns[u'jörn'].startswith(ns)) + + class NamespacePrefixTest(unittest.TestCase): def test_compute_qname(self): """Test sequential assignment of unknown prefixes"""