Pierre Carbonnelle committed 70b38e3

remove dependency on the six package

Comments (0)

Files changed (6)


 from decimal import Decimal
 import math
 import re
-import six
 import datetime
 from pyDatalog import pyDatalog


 import time
-import six
 from pyDatalog import pyDatalog
 def test1():


 from itertools import groupby
 import logging
 import re
-import six
-from six.moves import xrange
 import threading
 import weakref
         """ factory function for interned objects """
         if isinstance(atom, (Interned, Fresh_var, Operation)):
             return atom
-        elif isinstance(atom, (list, tuple, xrange)):
+        elif isinstance(atom, (list, tuple, util.xrange)):
             return VarTuple(tuple([Interned.of(element) for element in atom]))
             return Const(atom)
     registry = weakref.WeakValueDictionary()
     counter = util.Counter()
     def __new__(cls,  _id):
-        r = repr(_id) if isinstance(_id, (six.string_types, float, Decimal)) else _id
+        r = repr(_id) if isinstance(_id, (util.string_types, float, Decimal)) else _id
         with Const.lock:
             o = cls.registry.get(r, Interned.notFound)
             if o is Interned.notFound: 
         It can also have a function used to implement a primitive."""
     lock = threading.RLock()
     def __new__(cls, pred_name, arity, aggregate=None):
-        assert isinstance(pred_name, six.string_types)
+        assert isinstance(pred_name, util.string_types)
         _id = '%s/%i' % (pred_name, arity)
         with Pred.lock:
             o =, Interned.notFound)
     __slots__ = ['terms', 'pred', 'id', 'key', 'tag']
     def __init__(self, pred, terms, prearity=None, aggregate=None):
         self.terms = terms
-        if isinstance(pred, six.string_types):
+        if isinstance(pred, util.string_types):
             self.pred = Pred(pred, len(terms), aggregate)
             self.pred.prearity = prearity or len(terms)
             if pred[:1] == '~': #pred


 import ast
 from collections import OrderedDict
 import inspect
-import itertools
 import re
 import string
-import six
-from six.moves import builtins, xrange
 import sys
 import threading
         if in (True, [], [()]): return str(self._data)
         # get the widths of each column
         widths = [max(len(str(x)) for x in column) for column in zip(*(self._data))]
-        widths = [max(widths[i], len(str(self.variables[i]))) for i in xrange(len(widths))]
+        widths = [max(widths[i], len(str(self.variables[i]))) for i in util.xrange(len(widths))]
         # get the formating string
-        fofo = ' | '.join('%%-%ss' % widths[i] for i in xrange(len(widths)))
+        fofo = ' | '.join('%%-%ss' % widths[i] for i in util.xrange(len(widths)))
         return '\n'.join((fofo % self.variables, 
-                            '-|-'.join( widths[i]*'-' for i in xrange(len(widths))),
+                            '-|-'.join( widths[i]*'-' for i in util.xrange(len(widths))),
                             '\n'.join(fofo % s for s in self._data)))
     def __init__ (self, name, forced_type=None):
         self._pyD_negated = False # for aggregate with sort in descending order
         self._pyD_precalculations = Body() # no precalculations
-        if isinstance(name, (list, tuple, xrange)):
+        if isinstance(name, (list, tuple, util.xrange)):
             self._pyD_value = list(map(Expression._for, name))
             self._pyD_name = str([element._pyD_name for element in self._pyD_value])
             self._pyD_type = 'tuple'
         if not all([isinstance(e, VarSymbol) for e in self.order_by]):
             raise util.DatalogError("order_by argument of aggregate must be variable(s).", None, None)
-        if sep and not isinstance(sep, six.string_types):
+        if sep and not isinstance(sep, util.string_types):
             raise util.DatalogError("Separator in aggregation must be a string", None, None)
         self.sep = sep
     newglobals, defined = newglobals or {}, defined or set([])
     # remove indentation based on first non-blank line
-    lines = code.splitlines() if isinstance(code, six.string_types) else code
+    lines = code.splitlines() if isinstance(code, util.string_types) else code
     r = re.compile('^\s*')
     for line in lines:
         spaces = r.match(line).group()
         e.function = function
         e.message = e.value
         e.value = "%s\n%s" % (e.value, lines[e.lineno-1])
-        six.reraise(*sys.exc_info())
+        util.reraise(*sys.exc_info())
     code = compile(tree, function, 'exec')
-    defined = defined.union(dir(builtins))
+    defined = defined.union(dir(util.builtins))
     for name in set(code.co_names).difference(defined): # for names that are not defined
         add_symbols((name,), newglobals)
         with ProgramContext():
-            six.exec_(code, newglobals)
+            util.exec_(code, newglobals)
     except util.DatalogError as e:
         e.function = function
         traceback = sys.exc_info()[2]
                 traceback = traceback.tb_next 
         e.message = e.value
         e.value = "%s\n%s" % (e.value, lines[e.lineno-1])
-        six.reraise(*sys.exc_info())
+        util.reraise(*sys.exc_info())
 class _NoCallFunction(object):
     """ This class prevents a call to a datalog program created using the 'program' decorator """

+import sys
 import threading
 class DatalogError(Exception):
             self.i += 1
             return self.i
+###################### support for Python 2 and 3 ####################################
+# inspired by the six library
+PY2 = sys.version_info[0] == 2
+if PY2:
+    string_types = basestring,
+    import __builtin__ as builtins
+    xrange = builtins.xrange
+    string_types = str,
+    xrange = range
+if PY2:
+    def exec_(_code_, _globs_=None, _locs_=None):
+        """Execute code in a namespace."""
+        if _globs_ is None:
+            frame = sys._getframe(1)
+            _globs_ = frame.f_globals
+            if _locs_ is None:
+                _locs_ = frame.f_locals
+            del frame
+        elif _locs_ is None:
+            _locs_ = _globs_
+        exec("""exec _code_ in _globs_, _locs_""")
+    exec_("""def reraise(tp, value, tb=None):
+    raise tp, value, tb
+    """)
+    import builtins
+    exec_ = getattr(builtins, "exec")
+    def reraise(tp, value, tb=None):
+        if value.__traceback__ is not tb:
+            raise value.with_traceback(tb)
+        raise value
 Datalog is a truly declarative language derived from Prolog, with strong academic foundations.  It complements Python very well for:
-* managing large sets of related information (e.g. in data integration or the semantic web).  
+* managing complex sets of related information (e.g. in data integration or the semantic web).  
 * simulating intelligent behavior (e.g. in games), 
 * performing recursive algorithms (e.g. in network protocol, code and graph analysis, parsing)
 * solving discrete constraint problems. 
 * it can perform multi-database queries (from memory datastore, 11 relational databases, and noSQL database with appropriate connectors)
 * it is more expressive than SQL, with a cleaner syntax; 
 * it facilitates re-use of SQL code snippet (e.g. for frequent joins or formula); 
-* it offloads the database server by performing joins on the application tier. 
 Datalog excels at accelerated development : Datalog programs are often shorter than their Python equivalent, 
-and Datalog statements can be specified in any order, as simply as formula in a spreadsheet.""",
-    setup_requires = ["six"],
-    install_requires = ["six"]
+and Datalog statements can be specified in any order, as simply as formula in a spreadsheet."""