diff options
author | Gunnar Aastrand Grimnes <gromgull@gmail.com> | 2017-01-27 19:10:53 +0100 |
---|---|---|
committer | Gunnar Aastrand Grimnes <gromgull@gmail.com> | 2017-01-27 19:10:53 +0100 |
commit | 3d531734c85ccc0a51889744ca59b112a6cd01ae (patch) | |
tree | f2a80f0242fe697e8fb774f0af68b9e86e6382ff | |
parent | 4204d6b4e0e0cd9a5e1be6460eeef296bc5161df (diff) | |
download | rdflib-3d531734c85ccc0a51889744ca59b112a6cd01ae.tar.gz |
removed compat code for supporting legacy python versions
-rw-r--r-- | rdflib/__init__.py | 2 | ||||
-rw-r--r-- | rdflib/compare.py | 8 | ||||
-rw-r--r-- | rdflib/compat.py | 49 | ||||
-rw-r--r-- | rdflib/plugins/serializers/turtle.py | 2 | ||||
-rw-r--r-- | rdflib/plugins/sparql/compat.py | 25 | ||||
-rw-r--r-- | rdflib/plugins/sparql/parserutils.py | 2 | ||||
-rw-r--r-- | rdflib/plugins/sparql/results/jsonlayer.py | 163 | ||||
-rw-r--r-- | rdflib/plugins/sparql/results/jsonresults.py | 8 | ||||
-rw-r--r-- | rdflib/plugins/sparql/sparql.py | 5 | ||||
-rw-r--r-- | rdflib/term.py | 3 | ||||
-rw-r--r-- | rdflib/tools/graphisomorphism.py | 27 |
11 files changed, 13 insertions, 281 deletions
diff --git a/rdflib/__init__.py b/rdflib/__init__.py index 0e6006c7..a661f27d 100644 --- a/rdflib/__init__.py +++ b/rdflib/__init__.py @@ -69,7 +69,7 @@ __all__ = [ ] import sys -assert sys.version_info >= (2, 5, 0), "rdflib requires Python 2.5 or higher" +assert sys.version_info >= (2, 7, 0), "rdflib requires Python 2.7 or higher" import logging _interactive_mode = False diff --git a/rdflib/compare.py b/rdflib/compare.py index c7ab6329..2cb26f00 100644 --- a/rdflib/compare.py +++ b/rdflib/compare.py @@ -85,13 +85,7 @@ __all__ = ['IsomorphicGraph', 'to_isomorphic', 'isomorphic', from rdflib.graph import Graph, ConjunctiveGraph, ReadOnlyGraphAggregate from rdflib.term import BNode, Node -try: - import hashlib - sha256 = hashlib.sha256 -except ImportError: - # for Python << 2.5 - import sha256 - sha256 = sha256.new +from hashlib import sha256 from datetime import datetime from collections import defaultdict diff --git a/rdflib/compat.py b/rdflib/compat.py index bb085dd0..33b569bd 100644 --- a/rdflib/compat.py +++ b/rdflib/compat.py @@ -2,29 +2,6 @@ # code to simplify supporting older python versions # - -import sys - -from decimal import Decimal - -if sys.version_info[:2] < (2, 7): - - # Pre-2.7 decimal and float did not compare correctly - - def numeric_greater(a, b): - if isinstance(a, Decimal) and isinstance(b, float): - return float(a) > b - elif isinstance(a, float) and isinstance(b, Decimal): - return a > float(b) - else: - return a > b - -else: - - def numeric_greater(a, b): - return a > b - - try: from lxml import etree except ImportError: @@ -54,29 +31,3 @@ except AttributeError: def etree_register_namespace(prefix, uri): etreenative._namespace_map[uri] = prefix - -try: - from functools import cmp_to_key -except ImportError: - # Backport from Py2.7 for Py2.6: - def cmp_to_key(mycmp): - """Convert a cmp= function into a key= function""" - class K(object): - __slots__ = ['obj'] - def __init__(self, obj, *args): - self.obj = obj - def __lt__(self, other): - return mycmp(self.obj, other.obj) < 0 - def __gt__(self, other): - return mycmp(self.obj, other.obj) > 0 - def __eq__(self, other): - return mycmp(self.obj, other.obj) == 0 - def __le__(self, other): - return mycmp(self.obj, other.obj) <= 0 - def __ge__(self, other): - return mycmp(self.obj, other.obj) >= 0 - def __ne__(self, other): - return mycmp(self.obj, other.obj) != 0 - def __hash__(self): - raise TypeError('hash not implemented') - return K diff --git a/rdflib/plugins/serializers/turtle.py b/rdflib/plugins/serializers/turtle.py index 9027ed3d..67568ee3 100644 --- a/rdflib/plugins/serializers/turtle.py +++ b/rdflib/plugins/serializers/turtle.py @@ -4,8 +4,8 @@ See <http://www.w3.org/TeamSubmission/turtle/> for syntax specification. """ from collections import defaultdict +from functools import cmp_to_key -from rdflib.compat import cmp_to_key from rdflib.term import BNode, Literal, URIRef from rdflib.exceptions import Error from rdflib.serializer import Serializer diff --git a/rdflib/plugins/sparql/compat.py b/rdflib/plugins/sparql/compat.py deleted file mode 100644 index bb8e250a..00000000 --- a/rdflib/plugins/sparql/compat.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -Function/methods to help supporting 2.5-2.7 -""" - -# Collection ABCs - -try: - from collections import Mapping, MutableMapping # was added in 2.6 - -except: - from UserDict import DictMixin - - class MutableMapping(DictMixin): - def keys(self): - return list(self) - - Mapping = MutableMapping - - -# OrderedDict - -try: - from collections import OrderedDict # was added in 2.7 -except ImportError: - from ordereddict import OrderedDict # extra module diff --git a/rdflib/plugins/sparql/parserutils.py b/rdflib/plugins/sparql/parserutils.py index 7e4a3665..cad1bfaf 100644 --- a/rdflib/plugins/sparql/parserutils.py +++ b/rdflib/plugins/sparql/parserutils.py @@ -1,7 +1,7 @@ from types import MethodType -from rdflib.plugins.sparql.compat import OrderedDict +from collections import OrderedDict from pyparsing import TokenConverter, ParseResults diff --git a/rdflib/plugins/sparql/results/jsonlayer.py b/rdflib/plugins/sparql/results/jsonlayer.py deleted file mode 100644 index 73720850..00000000 --- a/rdflib/plugins/sparql/results/jsonlayer.py +++ /dev/null @@ -1,163 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright (C) 2009 Christopher Lenz -# All rights reserved. -# - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: - -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# 3. The name of the author may not be used to endorse or promote -# products derived from this software without specific prior -# written permission. - -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Thin abstraction layer over the different available modules for decoding -and encoding JSON data. - -This module currently supports the following JSON modules: - - ``simplejson``: http://code.google.com/p/simplejson/ - - ``cjson``: http://pypi.python.org/pypi/python-cjson - - ``json``: This is the version of ``simplejson`` that is bundled with the - Python standard library since version 2.6 - (see http://docs.python.org/library/json.html) - -The default behavior is to use ``simplejson`` if installed, and otherwise -fallback to the standard library module. To explicitly tell SPARQLWrapper -which module to use, invoke the `use()` function with the module name:: - - import jsonlayer - jsonlayer.use('cjson') - -In addition to choosing one of the above modules, you can also configure -SPARQLWrapper to use custom decoding and encoding functions:: - - import jsonlayer - jsonlayer.use(decode=my_decode, encode=my_encode) - -""" - -__all__ = ['decode', 'encode', 'use'] - -_initialized = False -_using = None -_decode = None -_encode = None - - -def decode(string): - """Decode the given JSON string. - - :param string: the JSON string to decode - :type string: basestring - :return: the corresponding Python data structure - :rtype: object - """ - if not _initialized: - _initialize() - return _decode(string) - - -def encode(obj): - """Encode the given object as a JSON string. - - :param obj: the Python data structure to encode - :type obj: object - :return: the corresponding JSON string - :rtype: basestring - """ - if not _initialized: - _initialize() - return _encode(obj) - - -def use(module=None, decode=None, encode=None): - """Set the JSON library that should be used, either by specifying a known - module name, or by providing a decode and encode function. - - The modules "simplejson", "cjson", and "json" are currently supported for - the ``module`` parameter. - - If provided, the ``decode`` parameter must be a callable that accepts a - JSON string and returns a corresponding Python data structure. The - ``encode`` callable must accept a Python data structure and return the - corresponding JSON string. Exceptions raised by decoding and encoding - should be propagated up unaltered. - - :param module: the name of the JSON library module to use, or the module - object itself - :type module: str or module - :param decode: a function for decoding JSON strings - :type decode: callable - :param encode: a function for encoding objects as JSON strings - :type encode: callable - """ - global _decode, _encode, _initialized, _using - if module is not None: - if not isinstance(module, basestring): - module = module.__name__ - if module not in ('cjson', 'json', 'simplejson'): - raise ValueError('Unsupported JSON module %s' % module) - _using = module - _initialized = False - else: - assert decode is not None and encode is not None - _using = 'custom' - _decode = decode - _encode = encode - _initialized = True - - -def _initialize(): - global _initialized - - def _init_simplejson(): - global _decode, _encode - import simplejson - _decode = lambda string, loads=simplejson.loads: loads(string) - _encode = lambda obj, dumps=simplejson.dumps: \ - dumps(obj, allow_nan=False, ensure_ascii=False) - - def _init_cjson(): - global _decode, _encode - import cjson - _decode = lambda string, decode=cjson.decode: decode(string) - _encode = lambda obj, encode=cjson.encode: encode(obj) - - def _init_stdlib(): - global _decode, _encode - json = __import__('json', {}, {}) - _decode = lambda string, loads=json.loads: loads(string) - _encode = lambda obj, dumps=json.dumps: \ - dumps(obj, allow_nan=False, ensure_ascii=False) - - if _using == 'simplejson': - _init_simplejson() - elif _using == 'cjson': - _init_cjson() - elif _using == 'json': - _init_stdlib() - elif _using != 'custom': - try: - _init_simplejson() - except ImportError: - _init_stdlib() - _initialized = True diff --git a/rdflib/plugins/sparql/results/jsonresults.py b/rdflib/plugins/sparql/results/jsonresults.py index aca8a0f4..13510175 100644 --- a/rdflib/plugins/sparql/results/jsonresults.py +++ b/rdflib/plugins/sparql/results/jsonresults.py @@ -1,3 +1,5 @@ +import json + from rdflib.query import ( Result, ResultException, ResultSerializer, ResultParser) from rdflib import Literal, URIRef, BNode, Variable @@ -5,8 +7,6 @@ from rdflib import Literal, URIRef, BNode, Variable from rdflib.py3compat import bytestype -import jsonlayer - """A Serializer for SPARQL results in JSON: http://www.w3.org/TR/rdf-sparql-json-res/ @@ -25,7 +25,7 @@ class JSONResultParser(ResultParser): inp = source.read() if isinstance(inp, bytestype): inp = inp.decode('utf-8') - return JSONResult(jsonlayer.decode(inp)) + return JSONResult(json.loads(inp)) class JSONResultSerializer(ResultSerializer): @@ -47,7 +47,7 @@ class JSONResultSerializer(ResultSerializer): res["results"]["bindings"] = [self._bindingToJSON( x) for x in self.result.bindings] - r = jsonlayer.encode(res) + r = json.dumps(res, allow_nan=False, ensure_ascii=False) if encoding is not None: stream.write(r.encode(encoding)) else: diff --git a/rdflib/plugins/sparql/sparql.py b/rdflib/plugins/sparql/sparql.py index c012a8fc..e92f5b4e 100644 --- a/rdflib/plugins/sparql/sparql.py +++ b/rdflib/plugins/sparql/sparql.py @@ -1,15 +1,16 @@ import collections import itertools import datetime +from collections import Mapping, MutableMapping from rdflib.namespace import NamespaceManager from rdflib import Variable, BNode, Graph, ConjunctiveGraph, URIRef, Literal from rdflib.term import Node -from parserutils import CompValue +from rdflib.plugins.sparql.parserutils import CompValue import rdflib.plugins.sparql -from rdflib.plugins.sparql.compat import Mapping, MutableMapping + class SPARQLError(Exception): diff --git a/rdflib/term.py b/rdflib/term.py index 2bdad22a..623dcfe2 100644 --- a/rdflib/term.py +++ b/rdflib/term.py @@ -59,7 +59,6 @@ except ImportError: import rdflib from . import py3compat -from rdflib.compat import numeric_greater b = py3compat.b @@ -785,7 +784,7 @@ class Literal(Identifier): if self.datatype in _NUMERIC_LITERAL_TYPES and \ other.datatype in _NUMERIC_LITERAL_TYPES: - return numeric_greater(self.value, other.value) + return self.value>other.value # plain-literals and xsd:string literals # are "the same" diff --git a/rdflib/tools/graphisomorphism.py b/rdflib/tools/graphisomorphism.py index 04cf25fc..09518110 100644 --- a/rdflib/tools/graphisomorphism.py +++ b/rdflib/tools/graphisomorphism.py @@ -5,32 +5,7 @@ if BNode labels are ignored. from rdflib.graph import Graph from rdflib import BNode -try: - from itertools import combinations - assert combinations -except ImportError: # Python == 2.5 - # Copied from - # http://docs.python.org/2/library/itertools.html#itertools.combinations - def combinations(iterable, r): - # combinations('ABCD', 2) --> AB AC AD BC BD CD - # combinations(range(4), 3) --> 012 013 023 123 - pool = tuple(iterable) - n = len(pool) - if r > n: - return - indices = range(r) - yield tuple(pool[i] for i in indices) - while True: - for i in reversed(range(r)): - if indices[i] != i + n - r: - break - else: - return - indices[i] += 1 - for j in range(i + 1, r): - indices[j] = indices[j - 1] + 1 - yield tuple(pool[i] for i in indices) - +from itertools import combinations class IsomorphicTestableGraph(Graph): """ |