summaryrefslogtreecommitdiff
path: root/rdflib/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'rdflib/plugins')
-rw-r--r--rdflib/plugins/memory.py6
-rwxr-xr-xrdflib/plugins/parsers/notation3.py37
-rw-r--r--rdflib/plugins/parsers/nquads.py3
-rw-r--r--rdflib/plugins/parsers/ntriples.py14
-rw-r--r--rdflib/plugins/parsers/rdfxml.py2
-rw-r--r--rdflib/plugins/parsers/trix.py6
-rw-r--r--rdflib/plugins/serializers/nquads.py3
-rw-r--r--rdflib/plugins/serializers/nt.py3
-rw-r--r--rdflib/plugins/serializers/rdfxml.py6
-rw-r--r--rdflib/plugins/serializers/trig.py3
-rw-r--r--rdflib/plugins/serializers/trix.py19
-rw-r--r--rdflib/plugins/serializers/turtle.py7
-rw-r--r--rdflib/plugins/sleepycat.py41
-rw-r--r--rdflib/plugins/sparql/aggregates.py8
-rw-r--r--rdflib/plugins/sparql/evaluate.py6
-rw-r--r--rdflib/plugins/sparql/operators.py18
-rw-r--r--rdflib/plugins/sparql/parser.py11
-rw-r--r--rdflib/plugins/sparql/processor.py4
-rw-r--r--rdflib/plugins/sparql/results/csvresults.py21
-rw-r--r--rdflib/plugins/sparql/results/jsonresults.py10
-rw-r--r--rdflib/plugins/sparql/results/tsvresults.py4
-rw-r--r--rdflib/plugins/sparql/results/xmlresults.py9
-rw-r--r--rdflib/plugins/sparql/sparql.py23
-rw-r--r--rdflib/plugins/sparql/update.py9
-rw-r--r--rdflib/plugins/stores/regexmatching.py6
-rw-r--r--rdflib/plugins/stores/sparqlstore.py7
26 files changed, 118 insertions, 168 deletions
diff --git a/rdflib/plugins/memory.py b/rdflib/plugins/memory.py
index 6741e316..1c1161e9 100644
--- a/rdflib/plugins/memory.py
+++ b/rdflib/plugins/memory.py
@@ -4,9 +4,7 @@ from __future__ import print_function
import random
-from rdflib.term import BNode
from rdflib.store import Store, NO_STORE, VALID_STORE
-from six import iteritems
__all__ = ['Memory', 'IOMemory']
@@ -167,7 +165,7 @@ class Memory(Store):
return self.__prefix.get(namespace, None)
def namespaces(self):
- for prefix, namespace in iteritems(self.__namespace):
+ for prefix, namespace in self.__namespace.items():
yield prefix, namespace
def __contexts(self):
@@ -247,7 +245,7 @@ class IOMemory(Store):
return self.__prefix.get(namespace, None)
def namespaces(self):
- for prefix, namespace in iteritems(self.__namespace):
+ for prefix, namespace in self.__namespace.items():
yield prefix, namespace
def add(self, triple, context, quoted=False):
diff --git a/rdflib/plugins/parsers/notation3.py b/rdflib/plugins/parsers/notation3.py
index c57f5bcf..44a25adc 100755
--- a/rdflib/plugins/parsers/notation3.py
+++ b/rdflib/plugins/parsers/notation3.py
@@ -45,14 +45,7 @@ from uuid import uuid4
from rdflib.term import URIRef, BNode, Literal, Variable, _XSD_PFX, _unique_id
from rdflib.graph import QuotedGraph, ConjunctiveGraph, Graph
-
-from six import b
-from six import binary_type
-
from rdflib.compat import long_type
-from six import string_types
-from six import text_type
-from six import unichr
from rdflib.compat import narrow_build
__all__ = ['BadSyntax', 'N3Parser', 'TurtleParser',
@@ -84,7 +77,6 @@ def splitFragP(uriref, punct=0):
return uriref, ''
-
def join(here, there):
"""join an absolute URI and URI reference
(non-ascii characters are supported/doctested;
@@ -126,7 +118,7 @@ def join(here, there):
slashl = there.find('/')
colonl = there.find(':')
- # join(base, 'foo:/') -- absolute
+ # join(base, 'foo:/') -- absolute
if colonl >= 0 and (slashl < 0 or colonl < slashl):
return there
@@ -138,7 +130,7 @@ def join(here, there):
if not path:
return here + frag
- # join('mid:foo@example', '../foo') bzzt
+ # join('mid:foo@example', '../foo') bzzt
if here[bcolonl + 1:bcolonl + 2] != '/':
raise ValueError(
("Base <%s> has no slash after "
@@ -149,16 +141,16 @@ def join(here, there):
else:
bpath = bcolonl + 1
- # join('http://xyz', 'foo')
+ # join('http://xyz', 'foo')
if bpath < 0:
bpath = len(here)
here = here + '/'
- # join('http://xyz/', '//abc') => 'http://abc'
+ # join('http://xyz/', '//abc') => 'http://abc'
if there[:2] == '//':
return here[:bcolonl + 1] + there
- # join('http://xyz/', '/abc') => 'http://xyz/abc'
+ # join('http://xyz/', '/abc') => 'http://xyz/abc'
if there[:1] == '/':
return here[:bpath] + there
@@ -190,7 +182,7 @@ def base():
we should put it in the hostname just to prevent ambiguity
"""
- # return "file://" + hostname + os.getcwd() + "/"
+ # return "file://" + hostname + os.getcwd() + "/"
return "file://" + _fixslash(os.getcwd()) + "/"
@@ -314,14 +306,14 @@ escapeChars = "(_~.-!$&'()*+,;=/?#@%)" # valid for \ escapes in localnames
def unicodeExpand(m):
try:
- return unichr(int(m.group(1), 16))
+ return chr(int(m.group(1), 16))
except:
raise Exception("Invalid unicode code point: " + m.group(1))
if narrow_build:
def unicodeExpand(m):
try:
- return unichr(int(m.group(1), 16))
+ return chr(int(m.group(1), 16))
except ValueError:
warnings.warn(
'Encountered a unicode char > 0xFFFF in a narrow python build. '
@@ -457,7 +449,7 @@ class SinkParser:
So if there is more data to feed to the
parser, it should be straightforward to recover."""
- if not isinstance(octets, text_type):
+ if not isinstance(octets, str):
s = octets.decode('utf-8')
# NB already decoded, so \ufeff
if len(s) > 0 and s[0] == codecs.BOM_UTF8.decode('utf-8'):
@@ -695,7 +687,7 @@ class SinkParser:
def bind(self, qn, uri):
assert isinstance(
- uri, binary_type), "Any unicode must be %x-encoded already"
+ uri, bytes), "Any unicode must be %x-encoded already"
if qn == "":
self._store.setDefaultNamespace(uri)
else:
@@ -1787,14 +1779,14 @@ class RDFSink(object):
def normalise(self, f, n):
if isinstance(n, tuple):
- return URIRef(text_type(n[1]))
+ return URIRef(str(n[1]))
if isinstance(n, bool):
s = Literal(str(n).lower(), datatype=BOOLEAN_DATATYPE)
return s
if isinstance(n, int) or isinstance(n, long_type):
- s = Literal(text_type(n), datatype=INTEGER_DATATYPE)
+ s = Literal(str(n), datatype=INTEGER_DATATYPE)
return s
if isinstance(n, Decimal):
@@ -1839,7 +1831,6 @@ class RDFSink(object):
#
-
def hexify(ustr):
"""Use URL encoding to return an ASCII string
corresponding to the given UTF8 string
@@ -1848,7 +1839,7 @@ def hexify(ustr):
%(b)s'http://example/a%%20b'
"""
- # s1=ustr.encode('utf-8')
+ # s1=ustr.encode('utf-8')
s = ""
for ch in ustr: # .encode('utf-8'):
if ord(ch) > 126 or ord(ch) < 33:
@@ -1856,7 +1847,7 @@ def hexify(ustr):
else:
ch = "%c" % ord(ch)
s = s + ch
- return b(s)
+ return s.encode("latin-1")
class TurtleParser(Parser):
diff --git a/rdflib/plugins/parsers/nquads.py b/rdflib/plugins/parsers/nquads.py
index 5857c9e4..8bc415bd 100644
--- a/rdflib/plugins/parsers/nquads.py
+++ b/rdflib/plugins/parsers/nquads.py
@@ -28,8 +28,6 @@ from __future__ import print_function
from codecs import getreader
-from six import b
-
from rdflib import ConjunctiveGraph
# Build up from the NTriples parser:
@@ -37,7 +35,6 @@ from rdflib.plugins.parsers.ntriples import NTriplesParser
from rdflib.plugins.parsers.ntriples import ParseError
from rdflib.plugins.parsers.ntriples import r_tail
from rdflib.plugins.parsers.ntriples import r_wspace
-from rdflib.plugins.parsers.ntriples import r_wspaces
__all__ = ['NQuadsParser']
diff --git a/rdflib/plugins/parsers/ntriples.py b/rdflib/plugins/parsers/ntriples.py
index 67dbe9d7..0724a86e 100644
--- a/rdflib/plugins/parsers/ntriples.py
+++ b/rdflib/plugins/parsers/ntriples.py
@@ -19,12 +19,8 @@ from rdflib.term import Literal
from rdflib.compat import cast_bytes
from rdflib.compat import decodeUnicodeEscape
-from rdflib.compat import ascii
-from six import BytesIO
-from six import string_types
-from six import text_type
-from six import unichr
+from io import BytesIO
__all__ = ['unquote', 'uriquote', 'Sink', 'NTriplesParser']
@@ -44,7 +40,7 @@ bufsiz = 2048
validate = False
-class Node(text_type):
+class Node(str):
pass
@@ -72,7 +68,7 @@ def unquote(s):
"""Unquote an N-Triples string."""
if not validate:
- if isinstance(s, text_type): # nquads
+ if isinstance(s, str): # nquads
s = decodeUnicodeEscape(s)
else:
s = s.decode('unicode-escape')
@@ -100,7 +96,7 @@ def unquote(s):
codepoint = int(u or U, 16)
if codepoint > 0x10FFFF:
raise ParseError("Disallowed codepoint: %08X" % codepoint)
- result.append(unichr(codepoint))
+ result.append(chr(codepoint))
elif s.startswith('\\'):
raise ParseError("Illegal escape at: %s..." % s[:10])
else:
@@ -158,7 +154,7 @@ class NTriplesParser(object):
def parsestring(self, s):
"""Parse s as an N-Triples string."""
- if not isinstance(s, string_types):
+ if not isinstance(s, str):
raise ParseError("Item to parse must be a string instance.")
f = BytesIO()
f.write(cast_bytes(s))
diff --git a/rdflib/plugins/parsers/rdfxml.py b/rdflib/plugins/parsers/rdfxml.py
index 810f3550..17554ba1 100644
--- a/rdflib/plugins/parsers/rdfxml.py
+++ b/rdflib/plugins/parsers/rdfxml.py
@@ -7,7 +7,7 @@ from xml.sax.handler import ErrorHandler
from xml.sax.saxutils import handler, quoteattr, escape
-from six.moves.urllib.parse import urldefrag, urljoin
+from urllib.parse import urldefrag, urljoin
from rdflib.namespace import RDF, is_ncname
from rdflib.term import URIRef
from rdflib.term import BNode
diff --git a/rdflib/plugins/parsers/trix.py b/rdflib/plugins/parsers/trix.py
index 26e0e35b..ffd883fe 100644
--- a/rdflib/plugins/parsers/trix.py
+++ b/rdflib/plugins/parsers/trix.py
@@ -8,7 +8,7 @@ from rdflib.term import Literal
from rdflib.graph import Graph, ConjunctiveGraph
from rdflib.exceptions import ParserError
from rdflib.parser import Parser
-from six import text_type
+
from xml.sax.saxutils import handler
from xml.sax import make_parser
@@ -98,7 +98,7 @@ class TriXHandler(handler.ContentHandler):
self.datatype = None
try:
- self.lang = attrs.getValue((text_type(XMLNS), u"lang"))
+ self.lang = attrs.getValue((str(XMLNS), u"lang"))
except:
# language not required - ignore
pass
@@ -115,7 +115,7 @@ class TriXHandler(handler.ContentHandler):
self.lang = None
self.datatype = None
try:
- self.lang = attrs.getValue((text_type(XMLNS), u"lang"))
+ self.lang = attrs.getValue((str(XMLNS), u"lang"))
except:
# language not required - ignore
pass
diff --git a/rdflib/plugins/serializers/nquads.py b/rdflib/plugins/serializers/nquads.py
index 3785452b..a193e125 100644
--- a/rdflib/plugins/serializers/nquads.py
+++ b/rdflib/plugins/serializers/nquads.py
@@ -2,7 +2,6 @@ import warnings
from rdflib.term import Literal
from rdflib.serializer import Serializer
-from six import b
from rdflib.plugins.serializers.nt import _quoteLiteral
@@ -29,7 +28,7 @@ class NQuadsSerializer(Serializer):
for triple in context:
stream.write(_nq_row(
triple, context.identifier).encode(encoding, "replace"))
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
def _nq_row(triple, context):
diff --git a/rdflib/plugins/serializers/nt.py b/rdflib/plugins/serializers/nt.py
index ea2e2f32..95a88ae3 100644
--- a/rdflib/plugins/serializers/nt.py
+++ b/rdflib/plugins/serializers/nt.py
@@ -5,7 +5,6 @@ format.
"""
from rdflib.term import Literal
from rdflib.serializer import Serializer
-from six import b
import warnings
import codecs
@@ -30,7 +29,7 @@ class NTSerializer(Serializer):
encoding = self.encoding
for triple in self.store:
stream.write(_nt_row(triple).encode(self.encoding, "_rdflib_nt_escape"))
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
class NT11Serializer(NTSerializer):
diff --git a/rdflib/plugins/serializers/rdfxml.py b/rdflib/plugins/serializers/rdfxml.py
index 4242fc05..d3a705d2 100644
--- a/rdflib/plugins/serializers/rdfxml.py
+++ b/rdflib/plugins/serializers/rdfxml.py
@@ -9,10 +9,6 @@ from rdflib.util import first, more_than
from rdflib.collection import Collection
from rdflib.serializer import Serializer
-# from rdflib.exceptions import Error
-
-from six import b
-
from xml.sax.saxutils import quoteattr, escape
import xml.dom.minidom
@@ -223,7 +219,7 @@ class PrettyXMLSerializer(Serializer):
self.subject(subject, 1)
writer.pop(RDF.RDF)
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
# Set to None so that the memory can get garbage collected.
self.__serialized = None
diff --git a/rdflib/plugins/serializers/trig.py b/rdflib/plugins/serializers/trig.py
index 250e1c09..755587dc 100644
--- a/rdflib/plugins/serializers/trig.py
+++ b/rdflib/plugins/serializers/trig.py
@@ -7,7 +7,6 @@ from collections import defaultdict
from rdflib.plugins.serializers.turtle import TurtleSerializer, _GEN_QNAME_FOR_DT, VERB
from rdflib.term import BNode, Literal
-from six import b
__all__ = ['TrigSerializer']
@@ -95,4 +94,4 @@ class TrigSerializer(TurtleSerializer):
self.write('}\n')
self.endDocument()
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
diff --git a/rdflib/plugins/serializers/trix.py b/rdflib/plugins/serializers/trix.py
index 0a574493..e6651c70 100644
--- a/rdflib/plugins/serializers/trix.py
+++ b/rdflib/plugins/serializers/trix.py
@@ -6,7 +6,6 @@ from rdflib.namespace import Namespace
from rdflib.graph import Graph, ConjunctiveGraph
-from six import text_type, b
__all__ = ['TriXSerializer']
@@ -45,7 +44,7 @@ class TriXSerializer(Serializer):
raise Exception("Unknown graph type: " + type(self.store))
self.writer.pop()
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
def _writeGraph(self, graph):
self.writer.push(TRIXNS[u"graph"])
@@ -53,7 +52,7 @@ class TriXSerializer(Serializer):
self.writer.attribute("http://www.w3.org/XML/1998/namespacebase", graph.base)
if isinstance(graph.identifier, URIRef):
self.writer.element(
- TRIXNS[u"uri"], content=text_type(graph.identifier))
+ TRIXNS[u"uri"], content=str(graph.identifier))
for triple in graph.triples((None, None, None)):
self._writeTriple(triple)
@@ -64,22 +63,22 @@ class TriXSerializer(Serializer):
for component in triple:
if isinstance(component, URIRef):
self.writer.element(TRIXNS[u"uri"],
- content=text_type(component))
+ content=str(component))
elif isinstance(component, BNode):
self.writer.element(TRIXNS[u"id"],
- content=text_type(component))
+ content=str(component))
elif isinstance(component, Literal):
if component.datatype:
self.writer.element(TRIXNS[u"typedLiteral"],
- content=text_type(component),
+ content=str(component),
attributes={TRIXNS[u"datatype"]:
- text_type(component.datatype)})
+ str(component.datatype)})
elif component.language:
self.writer.element(TRIXNS[u"plainLiteral"],
- content=text_type(component),
+ content=str(component),
attributes={XMLNS[u"lang"]:
- text_type(component.language)})
+ str(component.language)})
else:
self.writer.element(TRIXNS[u"plainLiteral"],
- content=text_type(component))
+ content=str(component))
self.writer.pop()
diff --git a/rdflib/plugins/serializers/turtle.py b/rdflib/plugins/serializers/turtle.py
index 8a41587c..b89ff2d8 100644
--- a/rdflib/plugins/serializers/turtle.py
+++ b/rdflib/plugins/serializers/turtle.py
@@ -10,7 +10,6 @@ from rdflib.term import BNode, Literal, URIRef
from rdflib.exceptions import Error
from rdflib.serializer import Serializer
from rdflib.namespace import RDF, RDFS
-from six import b, text_type
__all__ = ['RecursiveSerializer', 'TurtleSerializer']
@@ -32,8 +31,8 @@ def _object_comparator(a, b):
return 0
except TypeError:
- a = text_type(a)
- b = text_type(b)
+ a = str(a)
+ b = str(b)
return (a > b) - (a < b)
@@ -248,7 +247,7 @@ class TurtleSerializer(RecursiveSerializer):
self.write('\n')
self.endDocument()
- stream.write(b("\n"))
+ stream.write("\n".encode("latin-1"))
self.base = None
diff --git a/rdflib/plugins/sleepycat.py b/rdflib/plugins/sleepycat.py
index 745e270a..2d08b45b 100644
--- a/rdflib/plugins/sleepycat.py
+++ b/rdflib/plugins/sleepycat.py
@@ -4,8 +4,7 @@ from os.path import exists, abspath
from os import mkdir
from rdflib.store import Store, VALID_STORE, NO_STORE
from rdflib.term import URIRef
-from six import b
-from six.moves.urllib.request import pathname2url
+from urllib.request import pathname2url
def bb(u):
@@ -113,7 +112,7 @@ class Sleepycat(Store):
self.__indicies_info = [None, ] * 3
for i in range(0, 3):
index_name = to_key_func(
- i)((b("s"), b("p"), b("o")), b("c")).decode()
+ i)(("s".encode("latin-1"), "p".encode("latin-1"), "o".encode("latin-1")), "c".encode("latin-1")).decode()
index = db.DB(db_env)
index.set_flags(dbsetflags)
index.open(index_name, dbname, dbtype, dbopenflags, dbmode)
@@ -255,10 +254,10 @@ class Sleepycat(Store):
self.__contexts.put(bb(c), "", txn=txn)
contexts_value = cspo.get(
- bb("%s^%s^%s^%s^" % ("", s, p, o)), txn=txn) or b("")
- contexts = set(contexts_value.split(b("^")))
+ bb("%s^%s^%s^%s^" % ("", s, p, o)), txn=txn) or "".encode("latin-1")
+ contexts = set(contexts_value.split("^".encode("latin-1")))
contexts.add(bb(c))
- contexts_value = b("^").join(contexts)
+ contexts_value = "^".encode("latin-1").join(contexts)
assert contexts_value is not None
cspo.put(bb("%s^%s^%s^%s^" % (c, s, p, o)), "", txn=txn)
@@ -278,20 +277,20 @@ class Sleepycat(Store):
s, p, o = spo
cspo, cpos, cosp = self.__indicies
contexts_value = cspo.get(
- b("^").join([b(""), s, p, o, b("")]), txn=txn) or b("")
- contexts = set(contexts_value.split(b("^")))
+ "^".encode("latin-1").join(["".encode("latin-1"), s, p, o, "".encode("latin-1")]), txn=txn) or "".encode("latin-1")
+ contexts = set(contexts_value.split("^".encode("latin-1")))
contexts.discard(c)
- contexts_value = b("^").join(contexts)
+ contexts_value = "^".encode("latin-1").join(contexts)
for i, _to_key, _from_key in self.__indicies_info:
i.delete(_to_key((s, p, o), c), txn=txn)
if not quoted:
if contexts_value:
for i, _to_key, _from_key in self.__indicies_info:
- i.put(_to_key((s, p, o), b("")), contexts_value, txn=txn)
+ i.put(_to_key((s, p, o), "".encode("latin-1")), contexts_value, txn=txn)
else:
for i, _to_key, _from_key in self.__indicies_info:
try:
- i.delete(_to_key((s, p, o), b("")), txn=txn)
+ i.delete(_to_key((s, p, o), "".encode("latin-1")), txn=txn)
except db.DBNotFoundError:
pass # TODO: is it okay to ignore these?
@@ -344,11 +343,11 @@ class Sleepycat(Store):
if key.startswith(prefix):
c, s, p, o = from_key(key)
if context is None:
- contexts_value = index.get(key, txn=txn) or b("")
+ contexts_value = index.get(key, txn=txn) or "".encode("latin-1")
# remove triple from all non quoted contexts
- contexts = set(contexts_value.split(b("^")))
+ contexts = set(contexts_value.split("^".encode("latin-1")))
# and from the conjunctive index
- contexts.add(b(""))
+ contexts.add("".encode("latin-1"))
for c in contexts:
for i, _to_key, _ in self.__indicies_info:
i.delete(_to_key((s, p, o), c), txn=txn)
@@ -413,7 +412,7 @@ class Sleepycat(Store):
context = None
if context is None:
- prefix = b("^")
+ prefix = "^".encode("latin-1")
else:
prefix = bb("%s^" % self._to_string(context))
@@ -480,7 +479,7 @@ class Sleepycat(Store):
contexts = self.__indicies[0].get(bb(
"%s^%s^%s^%s^" % ("", s, p, o)))
if contexts:
- for c in contexts.split(b("^")):
+ for c in contexts.split("^".encode("latin-1")):
if c:
yield _from_string(c)
else:
@@ -553,18 +552,18 @@ class Sleepycat(Store):
def to_key_func(i):
def to_key(triple, context):
"Takes a string; returns key"
- return b("^").join(
+ return "^".encode("latin-1").join(
(context,
triple[i % 3],
triple[(i + 1) % 3],
- triple[(i + 2) % 3], b(""))) # "" to tac on the trailing ^
+ triple[(i + 2) % 3], "".encode("latin-1"))) # "" to tac on the trailing ^
return to_key
def from_key_func(i):
def from_key(key):
"Takes a key; returns string"
- parts = key.split(b("^"))
+ parts = key.split("^".encode("latin-1"))
return \
parts[0], \
parts[(3 - i + 0) % 3 + 1], \
@@ -576,7 +575,7 @@ def from_key_func(i):
def results_from_key_func(i, from_string):
def from_key(key, subject, predicate, object, contexts_value):
"Takes a key and subject, predicate, object; returns tuple for yield"
- parts = key.split(b("^"))
+ parts = key.split("^".encode("latin-1"))
if subject is None:
# TODO: i & 1: # dis assemble and/or measure to see which is faster
# subject is None or i & 1
@@ -592,7 +591,7 @@ def results_from_key_func(i, from_string):
else:
o = object
return (s, p, o), (
- from_string(c) for c in contexts_value.split(b("^")) if c)
+ from_string(c) for c in contexts_value.split("^".encode("latin-1")) if c)
return from_key
diff --git a/rdflib/plugins/sparql/aggregates.py b/rdflib/plugins/sparql/aggregates.py
index b63b6edb..11144778 100644
--- a/rdflib/plugins/sparql/aggregates.py
+++ b/rdflib/plugins/sparql/aggregates.py
@@ -1,6 +1,4 @@
from rdflib import Literal, XSD
-
-from six import text_type, itervalues
from rdflib.plugins.sparql.evalutils import _eval, NotBoundError, _val
from rdflib.plugins.sparql.operators import numeric
from rdflib.plugins.sparql.datatypes import type_promotion
@@ -225,7 +223,7 @@ class GroupConcat(Accumulator):
pass
def get_value(self):
- return Literal(self.separator.join(text_type(v) for v in self.value))
+ return Literal(self.separator.join(str(v) for v in self.value))
class Aggregator(object):
@@ -255,12 +253,12 @@ class Aggregator(object):
# SAMPLE accumulators may delete themselves
# => iterate over list not generator
- for acc in list(itervalues(self.accumulators)):
+ for acc in list(self.accumulators.values()):
if acc.use_row(row):
acc.update(row, self)
def get_bindings(self):
"""calculate and set last values"""
- for acc in itervalues(self.accumulators):
+ for acc in self.accumulators.values():
acc.set_value(self.bindings)
return self.bindings
diff --git a/rdflib/plugins/sparql/evaluate.py b/rdflib/plugins/sparql/evaluate.py
index cc6d35f9..fc9b0c30 100644
--- a/rdflib/plugins/sparql/evaluate.py
+++ b/rdflib/plugins/sparql/evaluate.py
@@ -21,8 +21,6 @@ import requests
from pyparsing import ParseException
from rdflib import Variable, Graph, BNode, URIRef, Literal
-from six import iteritems, itervalues
-
from rdflib.plugins.sparql import CUSTOM_EVALS
from rdflib.plugins.sparql.parserutils import value
from rdflib.plugins.sparql.sparql import (
@@ -377,7 +375,7 @@ def evalAggregateJoin(ctx, agg):
res[k].update(row)
# all rows are done; yield aggregated values
- for aggregator in itervalues(res):
+ for aggregator in res.values():
yield FrozenBindings(ctx, aggregator.get_bindings())
# there were no matches
@@ -498,7 +496,7 @@ def evalConstructQuery(ctx, query):
def evalQuery(graph, query, initBindings, base=None):
- initBindings = dict((Variable(k), v) for k, v in iteritems(initBindings))
+ initBindings = dict((Variable(k), v) for k, v in initBindings.items())
ctx = QueryContext(graph, initBindings=initBindings)
diff --git a/rdflib/plugins/sparql/operators.py b/rdflib/plugins/sparql/operators.py
index f904b82a..52558aa9 100644
--- a/rdflib/plugins/sparql/operators.py
+++ b/rdflib/plugins/sparql/operators.py
@@ -25,8 +25,8 @@ from rdflib.plugins.sparql.parserutils import CompValue, Expr
from rdflib.plugins.sparql.datatypes import XSD_DTs, type_promotion
from rdflib import URIRef, BNode, Variable, Literal, XSD, RDF
from rdflib.term import Node
-from six import text_type
-from six.moves.urllib.parse import quote
+
+from urllib.parse import quote
from pyparsing import ParseResults
@@ -218,7 +218,7 @@ def Builtin_REGEX(expr, ctx):
[('i', re.IGNORECASE), ('s', re.DOTALL), ('m', re.MULTILINE)])
cFlag = reduce(pyop.or_, [flagMap.get(f, 0) for f in flags])
- return Literal(bool(re.search(text_type(pattern), text, cFlag)))
+ return Literal(bool(re.search(str(pattern), text, cFlag)))
def Builtin_REPLACE(expr, ctx):
@@ -267,9 +267,9 @@ def Builtin_REPLACE(expr, ctx):
# this is necessary due to different treatment of unmatched groups in
# python versions. see comments above in _r(m).
- compat_r = text_type(replacement) if sys.version_info[:2] >= (3, 5) else _r
+ compat_r = str(replacement) if sys.version_info[:2] >= (3, 5) else _r
- return Literal(re.sub(text_type(pattern), compat_r, text, cFlag),
+ return Literal(re.sub(str(pattern), compat_r, text, cFlag),
datatype=text.datatype, lang=text.language)
@@ -278,7 +278,7 @@ def Builtin_STRDT(expr, ctx):
http://www.w3.org/TR/sparql11-query/#func-strdt
"""
- return Literal(text_type(expr.arg1), datatype=expr.arg2)
+ return Literal(str(expr.arg1), datatype=expr.arg2)
def Builtin_STRLANG(expr, ctx):
@@ -292,7 +292,7 @@ def Builtin_STRLANG(expr, ctx):
# TODO: normalisation of lang tag to lower-case
# should probably happen in literal __init__
- return Literal(text_type(s), lang=str(expr.arg2).lower())
+ return Literal(str(s), lang=str(expr.arg2).lower())
def Builtin_CONCAT(expr, ctx):
@@ -418,7 +418,7 @@ def Builtin_STR(e, ctx):
arg = e.arg
if isinstance(arg, SPARQLError):
raise arg
- return Literal(text_type(arg)) # plain literal
+ return Literal(str(arg)) # plain literal
def Builtin_LCASE(e, ctx):
@@ -436,7 +436,7 @@ def Builtin_LANGMATCHES(e, ctx):
langTag = string(e.arg1)
langRange = string(e.arg2)
- if text_type(langTag) == "":
+ if str(langTag) == "":
return Literal(False) # nothing matches empty!
return Literal(_lang_range_check(langRange, langTag))
diff --git a/rdflib/plugins/sparql/parser.py b/rdflib/plugins/sparql/parser.py
index 881e638b..cc785f4c 100644
--- a/rdflib/plugins/sparql/parser.py
+++ b/rdflib/plugins/sparql/parser.py
@@ -20,7 +20,6 @@ from .parserutils import Comp, Param, ParamList
from . import operators as op
from rdflib.compat import decodeUnicodeEscape
-from six import binary_type, unichr
import rdflib
@@ -195,7 +194,7 @@ PN_LOCAL_ESC_re = '\\\\[_~\\.\\-!$&"\'()*+,;=/?#@%]'
# [171] PERCENT ::= '%' HEX HEX
PERCENT_re = '%[0-9a-fA-F]{2}'
# PERCENT = Regex(PERCENT_re) # regex'd
-#PERCENT.setParseAction(lambda x: unichr(int(x[0][1:], 16)))
+#PERCENT.setParseAction(lambda x: chr(int(x[0][1:], 16)))
# [170] PLX ::= PERCENT | PN_LOCAL_ESC
PLX_re = '(%s|%s)' % (PN_LOCAL_ESC_re, PERCENT_re)
@@ -212,7 +211,7 @@ PN_LOCAL = Regex(u"""([%(PN_CHARS_U)s:0-9]|%(PLX)s)
def _hexExpand(match):
- return unichr(int(match.group(0)[1:], 16))
+ return chr(int(match.group(0)[1:], 16))
PN_LOCAL.setParseAction(lambda x: re.sub("(%s)" % PERCENT_re, _hexExpand, x[0]))
@@ -1043,7 +1042,7 @@ def expandUnicodeEscapes(q):
def expand(m):
try:
- return unichr(int(m.group(1), 16))
+ return chr(int(m.group(1), 16))
except:
raise Exception("Invalid unicode code point: " + m)
@@ -1053,7 +1052,7 @@ def expandUnicodeEscapes(q):
def parseQuery(q):
if hasattr(q, 'read'):
q = q.read()
- if isinstance(q, binary_type):
+ if isinstance(q, bytes):
q = q.decode('utf-8')
q = expandUnicodeEscapes(q)
@@ -1064,7 +1063,7 @@ def parseUpdate(q):
if hasattr(q, 'read'):
q = q.read()
- if isinstance(q, binary_type):
+ if isinstance(q, bytes):
q = q.decode('utf-8')
q = expandUnicodeEscapes(q)
diff --git a/rdflib/plugins/sparql/processor.py b/rdflib/plugins/sparql/processor.py
index 14f70f1b..073a387e 100644
--- a/rdflib/plugins/sparql/processor.py
+++ b/rdflib/plugins/sparql/processor.py
@@ -6,7 +6,7 @@ These should be automatically registered with RDFLib
"""
-from six import string_types
+
from rdflib.query import Processor, Result, UpdateProcessor
@@ -52,7 +52,7 @@ class SPARQLUpdateProcessor(UpdateProcessor):
self.graph = graph
def update(self, strOrQuery, initBindings={}, initNs={}):
- if isinstance(strOrQuery, string_types):
+ if isinstance(strOrQuery, str):
strOrQuery = translateUpdate(parseUpdate(strOrQuery), initNs=initNs)
return evalUpdate(self.graph, strOrQuery, initBindings)
diff --git a/rdflib/plugins/sparql/results/csvresults.py b/rdflib/plugins/sparql/results/csvresults.py
index 2cbeea05..d354ccf5 100644
--- a/rdflib/plugins/sparql/results/csvresults.py
+++ b/rdflib/plugins/sparql/results/csvresults.py
@@ -10,8 +10,6 @@ http://www.w3.org/TR/sparql11-results-csv-tsv/
import codecs
import csv
-from six import binary_type, PY3
-
from rdflib import Variable, BNode, URIRef, Literal
from rdflib.query import Result, ResultSerializer, ResultParser
@@ -25,7 +23,7 @@ class CSVResultParser(ResultParser):
r = Result('SELECT')
- if isinstance(source.read(0), binary_type):
+ if isinstance(source.read(0), bytes):
# if reading from source returns bytes do utf-8 decoding
source = codecs.getreader('utf-8')(source)
@@ -63,17 +61,14 @@ class CSVResultSerializer(ResultSerializer):
raise Exception(
"CSVSerializer can only serialize select query results")
- def serialize(self, stream, encoding='utf-8'):
+ def serialize(self, stream, encoding='utf-8', **kwargs):
- if PY3:
- # the serialiser writes bytes in the given encoding
- # in py3 csv.writer is unicode aware and writes STRINGS,
- # so we encode afterwards
- # in py2 it breaks when passed unicode strings,
- # and must be passed utf8, so we encode before
+ # the serialiser writes bytes in the given encoding
+ # in py3 csv.writer is unicode aware and writes STRINGS,
+ # so we encode afterwards
- import codecs
- stream = codecs.getwriter(encoding)(stream)
+ import codecs
+ stream = codecs.getwriter(encoding)(stream)
out = csv.writer(stream, delimiter=self.delim)
@@ -86,7 +81,5 @@ class CSVResultSerializer(ResultSerializer):
def serializeTerm(self, term, encoding):
if term is None:
return ""
- if not PY3:
- return term.encode(encoding)
else:
return term
diff --git a/rdflib/plugins/sparql/results/jsonresults.py b/rdflib/plugins/sparql/results/jsonresults.py
index 1f45ce27..6110c324 100644
--- a/rdflib/plugins/sparql/results/jsonresults.py
+++ b/rdflib/plugins/sparql/results/jsonresults.py
@@ -4,8 +4,6 @@ from rdflib.query import (
Result, ResultException, ResultSerializer, ResultParser)
from rdflib import Literal, URIRef, BNode, Variable
-from six import binary_type, text_type
-
"""A Serializer for SPARQL results in JSON:
@@ -23,7 +21,7 @@ class JSONResultParser(ResultParser):
def parse(self, source, content_type=None):
inp = source.read()
- if isinstance(inp, binary_type):
+ if isinstance(inp, bytes):
inp = inp.decode('utf-8')
return JSONResult(json.loads(inp))
@@ -114,13 +112,13 @@ def parseJsonTerm(d):
def termToJSON(self, term):
if isinstance(term, URIRef):
- return {'type': 'uri', 'value': text_type(term)}
+ return {'type': 'uri', 'value': str(term)}
elif isinstance(term, Literal):
r = {'type': 'literal',
- 'value': text_type(term)}
+ 'value': str(term)}
if term.datatype is not None:
- r['datatype'] = text_type(term.datatype)
+ r['datatype'] = str(term.datatype)
if term.language is not None:
r['xml:lang'] = term.language
return r
diff --git a/rdflib/plugins/sparql/results/tsvresults.py b/rdflib/plugins/sparql/results/tsvresults.py
index 6e9366f3..1395eaff 100644
--- a/rdflib/plugins/sparql/results/tsvresults.py
+++ b/rdflib/plugins/sparql/results/tsvresults.py
@@ -20,8 +20,6 @@ from rdflib.plugins.sparql.parserutils import Comp, Param, CompValue
from rdflib import Literal as RDFLiteral
-from six import binary_type
-
ParserElement.setDefaultWhitespaceChars(" \n")
@@ -49,7 +47,7 @@ HEADER.parseWithTabs()
class TSVResultParser(ResultParser):
def parse(self, source, content_type=None):
- if isinstance(source.read(0), binary_type):
+ if isinstance(source.read(0), bytes):
# if reading from source returns bytes do utf-8 decoding
source = codecs.getreader('utf-8')(source)
diff --git a/rdflib/plugins/sparql/results/xmlresults.py b/rdflib/plugins/sparql/results/xmlresults.py
index e1daff92..cdb81f76 100644
--- a/rdflib/plugins/sparql/results/xmlresults.py
+++ b/rdflib/plugins/sparql/results/xmlresults.py
@@ -6,7 +6,6 @@ from xml.dom import XML_NAMESPACE
from xml.sax.xmlreader import AttributesNSImpl
from rdflib.compat import etree
-from six import iteritems
from rdflib import Literal, URIRef, BNode, Graph, Variable
from rdflib.query import (
@@ -16,7 +15,7 @@ from rdflib.query import (
ResultException
)
-from six import text_type
+
SPARQL_XML_NAMESPACE = u'http://www.w3.org/2005/sparql-results#'
RESULTS_NS_ET = '{%s}' % SPARQL_XML_NAMESPACE
@@ -121,7 +120,7 @@ class XMLResultSerializer(ResultSerializer):
writer.write_results_header()
for b in self.result.bindings:
writer.write_start_result()
- for key, val in iteritems(b):
+ for key, val in b.items():
writer.write_binding(key, val)
writer.write_end_result()
@@ -154,7 +153,7 @@ class SPARQLXMLWriter:
u'head', AttributesNSImpl({}, {}))
for i in range(0, len(allvarsL)):
attr_vals = {
- (None, u'name'): text_type(allvarsL[i]),
+ (None, u'name'): str(allvarsL[i]),
}
attr_qnames = {
(None, u'name'): u'name',
@@ -196,7 +195,7 @@ class SPARQLXMLWriter:
assert self._resultStarted
attr_vals = {
- (None, u'name'): text_type(name),
+ (None, u'name'): str(name),
}
attr_qnames = {
(None, u'name'): u'name',
diff --git a/rdflib/plugins/sparql/sparql.py b/rdflib/plugins/sparql/sparql.py
index be980f44..d9d781db 100644
--- a/rdflib/plugins/sparql/sparql.py
+++ b/rdflib/plugins/sparql/sparql.py
@@ -5,7 +5,6 @@ import itertools
import datetime
import isodate
-from six import text_type, iteritems
from rdflib.compat import Mapping, MutableMapping
from rdflib.namespace import NamespaceManager
@@ -92,7 +91,7 @@ class Bindings(MutableMapping):
return "Bindings({" + ", ".join((k, self[k]) for k in self) + "})"
def __repr__(self):
- return text_type(self)
+ return str(self)
class FrozenDict(Mapping):
@@ -118,20 +117,20 @@ class FrozenDict(Mapping):
def __hash__(self):
# It would have been simpler and maybe more obvious to
- # use hash(tuple(sorted(self._d.iteritems()))) from this discussion
+ # use hash(tuple(sorted(self._d.items()))) from this discussion
# so far, but this solution is O(n). I don't know what kind of
# n we are going to run into, but sometimes it's hard to resist the
# urge to optimize when it will gain improved algorithmic performance.
if self._hash is None:
self._hash = 0
- for key, value in iteritems(self):
+ for key, value in self.items():
self._hash ^= hash(key)
self._hash ^= hash(value)
return self._hash
def project(self, vars):
return FrozenDict(
- (x for x in iteritems(self) if x[0] in vars))
+ (x for x in self.items() if x[0] in vars))
def disjointDomain(self, other):
return not bool(set(self).intersection(other))
@@ -148,7 +147,7 @@ class FrozenDict(Mapping):
def merge(self, other):
res = FrozenDict(
- itertools.chain(iteritems(self), iteritems(other)))
+ itertools.chain(self.items(), other.items()))
return res
@@ -180,11 +179,11 @@ class FrozenBindings(FrozenDict):
def project(self, vars):
return FrozenBindings(
- self.ctx, (x for x in iteritems(self) if x[0] in vars))
+ self.ctx, (x for x in self.items() if x[0] in vars))
def merge(self, other):
res = FrozenBindings(
- self.ctx, itertools.chain(iteritems(self), iteritems(other)))
+ self.ctx, itertools.chain(self.items(), other.items()))
return res
@@ -212,7 +211,7 @@ class FrozenBindings(FrozenDict):
# bindings from initBindings are newer forgotten
return FrozenBindings(
self.ctx, (
- x for x in iteritems(self) if (
+ x for x in self.items() if (
x[0] in _except or
x[0] in self.ctx.initBindings or
before[x[0]] is None)))
@@ -222,7 +221,7 @@ class FrozenBindings(FrozenDict):
return a frozen dict only of bindings in these
"""
return FrozenBindings(
- self.ctx, (x for x in iteritems(self) if x[0] in these))
+ self.ctx, (x for x in self.items() if x[0] in these))
class QueryContext(object):
@@ -322,10 +321,10 @@ class QueryContext(object):
if vars:
return FrozenBindings(
self, ((k, v)
- for k, v in iteritems(self.bindings)
+ for k, v in self.bindings.items()
if k in vars))
else:
- return FrozenBindings(self, iteritems(self.bindings))
+ return FrozenBindings(self, self.bindings.items())
def __setitem__(self, key, value):
if key in self.bindings and self.bindings[key] != value:
diff --git a/rdflib/plugins/sparql/update.py b/rdflib/plugins/sparql/update.py
index daf380a3..44ea40a3 100644
--- a/rdflib/plugins/sparql/update.py
+++ b/rdflib/plugins/sparql/update.py
@@ -5,9 +5,6 @@ Code for carrying out Update Operations
"""
from rdflib import Graph, Variable
-
-from six import iteritems
-
from rdflib.plugins.sparql.sparql import QueryContext
from rdflib.plugins.sparql.evalutils import _fillTemplate, _join
from rdflib.plugins.sparql.evaluate import evalBGP, evalPart
@@ -175,14 +172,14 @@ def evalModify(ctx, u):
if u.delete:
dg -= _fillTemplate(u.delete.triples, c)
- for g, q in iteritems(u.delete.quads):
+ for g, q in u.delete.quads.items():
cg = ctx.dataset.get_context(c.get(g))
cg -= _fillTemplate(q, c)
if u.insert:
dg += _fillTemplate(u.insert.triples, c)
- for g, q in iteritems(u.insert.quads):
+ for g, q in u.insert.quads.items():
cg = ctx.dataset.get_context(c.get(g))
cg += _fillTemplate(q, c)
@@ -277,7 +274,7 @@ def evalUpdate(graph, update, initBindings={}):
for u in update:
- initBindings = dict((Variable(k), v) for k, v in iteritems(initBindings))
+ initBindings = dict((Variable(k), v) for k, v in initBindings.items())
ctx = QueryContext(graph, initBindings=initBindings)
ctx.prologue = u.prologue
diff --git a/rdflib/plugins/stores/regexmatching.py b/rdflib/plugins/stores/regexmatching.py
index 773dfab3..55c1e671 100644
--- a/rdflib/plugins/stores/regexmatching.py
+++ b/rdflib/plugins/stores/regexmatching.py
@@ -11,7 +11,7 @@ matching against the results from the store it's wrapping.
from rdflib.store import Store
from rdflib.graph import Graph
-from six import text_type
+
import re
@@ -21,7 +21,7 @@ NATIVE_REGEX = 0
PYTHON_REGEX = 1
-class REGEXTerm(text_type):
+class REGEXTerm(str):
"""
REGEXTerm can be used in any term slot and is interpreted as a request to
perform a REGEX match (not a string comparison) using the value
@@ -32,7 +32,7 @@ class REGEXTerm(text_type):
self.compiledExpr = re.compile(expr)
def __reduce__(self):
- return (REGEXTerm, (text_type(''),))
+ return (REGEXTerm, (str(''),))
def regexCompareQuad(quad, regexQuad):
diff --git a/rdflib/plugins/stores/sparqlstore.py b/rdflib/plugins/stores/sparqlstore.py
index 4c93e213..989b0126 100644
--- a/rdflib/plugins/stores/sparqlstore.py
+++ b/rdflib/plugins/stores/sparqlstore.py
@@ -23,7 +23,6 @@ from rdflib import Variable, BNode
from rdflib.graph import DATASET_DEFAULT_GRAPH_ID
from rdflib.term import Node
-from six import string_types
BNODE_IDENT_PATTERN = re.compile('(?P<label>_\:[^\s]+)')
@@ -168,7 +167,7 @@ class SPARQLStore(SPARQLConnector, Store):
queryGraph=None,
DEBUG=False):
self.debug = DEBUG
- assert isinstance(query, string_types)
+ assert isinstance(query, str)
query = self._inject_prefixes(query, initNs)
@@ -362,7 +361,7 @@ class SPARQLStore(SPARQLConnector, Store):
"""
if (not self.context_aware) or (graph is None):
return False
- if isinstance(graph, string_types):
+ if isinstance(graph, str):
return graph != '__UNION__'
else:
return graph.identifier != DATASET_DEFAULT_GRAPH_ID
@@ -644,7 +643,7 @@ class SPARQLUpdateStore(SPARQLStore):
raise Exception("UpdateEndpoint is not set - call 'open'")
self.debug = DEBUG
- assert isinstance(query, string_types)
+ assert isinstance(query, str)
query = self._inject_prefixes(query, initNs)
if self._is_contextual(queryGraph):