RDFLib/rdflib — pull request #258 by dgerber (2013-03-28 13:44:59+00:00)
Title: Make string operations on URIRefs return URIRefs

Currently, concatenation, formatting or %-substitution demote URIRefs to unicode. It would be nice if they behaved like this instead:

In [13]: u = URIRef('/books/{book}/chapters/{chapter}')

In [14]: u.format(book='123', chapter=3)
Out[14]: rdflib.term.URIRef(u'/books/123/chapters/3')

In [15]: 'http://example.org' + _ + '#frag'
Out[15]: rdflib.term.URIRef(u'http://example.org/books/123/chapters/3#frag')

In [16]: URIRef('/books/%s/chapters/%s') % (23, 45)
Out[16]: rdflib.term.URIRef(u'/books/23/chapters/45')

Implementation:

class URIRef(Identifier):

def __add__(self, other):
return self.__class__(unicode(self) + other)

def __radd__(self, other):
return self.__class__(other + unicode(self))

def format(self, *args, **kwargs):
return self.__class__(unicode(self).format(*args, **kwargs))

def __mod__(self, other):
return self.__class__(unicode(self) % other)

This `__mod__` conflicts with property paths unary operators `*`, ? and + in rdflib_sparql. These could be expressed with (`*`, `__mul__`, same precedence as %) or (**, `__pow__`, higher precedence) instead.