Skip to content

Commit

Permalink
ENH: Make ClosedNamespace extend str like Namespace does
Browse files Browse the repository at this point in the history
Useful for testing URIRef is from a particular namespace
by means of:

    URIRef(...).startswith(NS)
               ^^^^^^^^^^^^^^^

where `URIRef.defrag()` currently wouldn't cut it.
  • Loading branch information
kernc committed Dec 14, 2020
1 parent c5ff127 commit 6477efd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
25 changes: 13 additions & 12 deletions rdflib/namespace.py
Expand Up @@ -172,18 +172,21 @@ def __repr__(self):
return "URIPattern(%r)" % str(self)


class ClosedNamespace(object):
class ClosedNamespace(str):
"""
A namespace with a closed list of members
Trying to create terms not listen is an error
Trying to create terms not listed is an error
"""

def __init__(self, uri, terms):
self.uri = uri
self.__uris = {}
for t in terms:
self.__uris[t] = URIRef(self.uri + t)
def __new__(cls, uri, terms):
try:
rt = super().__new__(cls, uri)
except UnicodeDecodeError:
rt = super().__new__(cls, uri, "utf-8")
rt.uri = uri # back-compat
rt.__uris = {t: URIRef(rt + t) for t in terms}
return rt

def term(self, name):
uri = self.__uris.get(name)
Expand All @@ -204,9 +207,6 @@ def __getattr__(self, name):
except KeyError as e:
raise AttributeError(e)

def __str__(self):
return str(self.uri)

def __repr__(self):
return "rdf.namespace.ClosedNamespace(%r)" % str(self.uri)

Expand All @@ -222,8 +222,9 @@ class _RDFNamespace(ClosedNamespace):
Closed namespace for RDF terms
"""

def __init__(self):
super(_RDFNamespace, self).__init__(
def __new__(cls):
return super().__new__(
cls,
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
terms=[
# Syntax Names
Expand Down
5 changes: 4 additions & 1 deletion test/test_namespace.py
Expand Up @@ -111,6 +111,9 @@ def add_not_in_namespace(s):

# a property name within the core FOAF namespace
self.assertEqual(
add_not_in_namespace("givenName"),
FOAF.givenName,
URIRef("http://xmlns.com/foaf/0.1/givenName"),
)

# namescape can be used as str
self.assertTrue(FOAF.givenName.startswith(FOAF))

0 comments on commit 6477efd

Please sign in to comment.