Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make namespace module flake8-compliant, change exceptions in that mod… #711

Merged
merged 2 commits into from
Feb 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 36 additions & 33 deletions rdflib/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@
from __future__ import division
from __future__ import print_function

import logging

import os
from unicodedata import category

from six import string_types
from six import text_type

from six.moves.urllib.request import pathname2url
from six.moves.urllib.parse import urldefrag
from six.moves.urllib.parse import urljoin

from rdflib.term import URIRef, Variable, _XSD_PFX, _is_valid_uri

__doc__ = """
===================
Namespace Utilities
Expand Down Expand Up @@ -58,26 +72,14 @@

"""

import logging
logger = logging.getLogger(__name__)

import os

from six import string_types
from six import text_type

from six.moves.urllib.request import pathname2url
from six.moves.urllib.parse import urldefrag
from six.moves.urllib.parse import urljoin

from rdflib.term import URIRef, Variable, _XSD_PFX, _is_valid_uri

__all__ = [
'is_ncname', 'split_uri', 'Namespace',
'ClosedNamespace', 'NamespaceManager',
'XMLNS', 'RDF', 'RDFS', 'XSD', 'OWL',
'SKOS', 'DOAP', 'FOAF', 'DC', 'DCTERMS', 'VOID']

logger = logging.getLogger(__name__)


class Namespace(text_type):

Expand All @@ -93,15 +95,13 @@ class Namespace(text_type):

"""


def __new__(cls, value):
try:
rt = text_type.__new__(cls, value)
except UnicodeDecodeError:
rt = text_type.__new__(cls, value, 'utf-8')
return rt


@property
def title(self):
return URIRef(self + 'title')
Expand All @@ -120,7 +120,7 @@ def __getattr__(self, name):
return self.term(name)

def __repr__(self):
return "Namespace(%s)"%text_type.__repr__(self)
return "Namespace(%r)" % text_type(self)


class URIPattern(text_type):
Expand Down Expand Up @@ -150,8 +150,7 @@ def format(self, *args, **kwargs):
return URIRef(text_type.format(self, *args, **kwargs))

def __repr__(self):
return "URIPattern(%r)"%text_type.__repr__(self)

return "URIPattern(%r)" % text_type(self)


class ClosedNamespace(object):
Expand All @@ -170,8 +169,9 @@ def __init__(self, uri, terms):
def term(self, name):
uri = self.__uris.get(name)
if uri is None:
raise Exception(
"term '%s' not in namespace '%s'" % (name, self.uri))
raise KeyError(
"term '{}' not in namespace '{}'".format(name, self.uri)
)
else:
return uri

Expand All @@ -185,10 +185,10 @@ def __getattr__(self, name):
return self.term(name)

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

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


class _RDFNamespace(ClosedNamespace):
Expand Down Expand Up @@ -226,8 +226,10 @@ def term(self, name):
except ValueError:
return super(_RDFNamespace, self).term(name)


RDF = _RDFNamespace()


RDFS = ClosedNamespace(
uri=URIRef("http://www.w3.org/2000/01/rdf-schema#"),
terms=[
Expand All @@ -248,7 +250,6 @@ def term(self, name):
VOID = Namespace('http://rdfs.org/ns/void#')



class NamespaceManager(object):
"""

Expand Down Expand Up @@ -329,17 +330,19 @@ def normalizeUri(self, rdfTerm):
def compute_qname(self, uri, generate=True):

if not _is_valid_uri(uri):
raise Exception('"%s" does not look like a valid URI, I cannot serialize this. Perhaps you wanted to urlencode it?'%uri)

raise ValueError(
'"{}" does not look like a valid URI, cannot serialize this. Did you want to urlencode it?'.format(uri)
)

if not uri in self.__cache:
if uri not in self.__cache:
namespace, name = split_uri(uri)
namespace = URIRef(namespace)
prefix = self.store.prefix(namespace)
if prefix is None:
if not generate:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was a great exception :D

raise Exception(
"No known prefix for %s and generate=False")
raise KeyError(
"No known prefix for {} and generate=False".format(namespace)
)
num = 1
while 1:
prefix = "ns%s" % num
Expand Down Expand Up @@ -403,8 +406,7 @@ def bind(self, prefix, namespace, override=True, replace=False):
elif bound_prefix == prefix:
pass # already bound
else:
if override or bound_prefix.startswith("_"): # or a generated
# prefix
if override or bound_prefix.startswith("_"): # or a generated prefix
self.store.bind(prefix, namespace)

def namespaces(self):
Expand Down Expand Up @@ -455,12 +457,12 @@ def absolutize(self, uri, defrag=1):
#
# * Characters '-' and '.' are allowed as name characters.

from unicodedata import category

NAME_START_CATEGORIES = ["Ll", "Lu", "Lo", "Lt", "Nl"]
NAME_CATEGORIES = NAME_START_CATEGORIES + ["Mc", "Me", "Mn", "Lm", "Nd"]
ALLOWED_NAME_CHARS = [u"\u00B7", u"\u0387", u"-", u".", u"_"]


# http://www.w3.org/TR/REC-xml-names/#NT-NCName
# [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus
# the ":" */
Expand All @@ -485,6 +487,7 @@ def is_ncname(name):
else:
return 0


XMLNS = "http://www.w3.org/XML/1998/namespace"


Expand All @@ -505,4 +508,4 @@ def split_uri(uri):
ln = uri[j:]
return (ns, ln)
break
raise Exception("Can't split '%s'" % uri)
raise ValueError("Can't split '{}'".format(uri))
2 changes: 1 addition & 1 deletion run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
spec of Nose, but with some options pre-set. To begin with, make sure you have
Nose installed, e.g.:

$ sudo easy_install nose
$ pip nose doctest-ignore-unicode

For daily test runs, use:

Expand Down