Reviewers: ,


Please review this at http://codereview.tryton.org/49005/

Affected files:
  M CHANGELOG
  M doc/topics/install.rst
  M setup.py
  M trytond/backend/sqlite/database.py
  M trytond/backend/sqlite/table.py
  M trytond/ir/translation.py
  M trytond/model/fields/one2many.py
  M trytond/model/model.py
  M trytond/model/modelsql.py
  M trytond/model/modelstorage.py
  M trytond/model/modelview.py
  M trytond/modules/__init__.py
  M trytond/protocols/datatype.py
  M trytond/pyson.py
  M trytond/security.py
  M trytond/tests/test_mptt.py
  M trytond/tests/test_tryton.py


Index: CHANGELOG
===================================================================

--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,4 @@
+* Drop support of Python 2.5
 * Remove support of zipped modules

 Version 2.0.0 - 2011-04-26

Index: doc/topics/install.rst
===================================================================

--- a/doc/topics/install.rst
+++ b/doc/topics/install.rst
@@ -7,7 +7,7 @@
 Prerequisites
 =============

-    * Python 2.5 or later (http://www.python.org/)
+    * Python 2.6 or later (http://www.python.org/)
     * lxml 2.0 or later (http://codespeak.net/lxml/)
     * relatorio 0.2.0 or later (http://relatorio.openhex.org/)
     * python-dateutil (http://labix.org/python-dateutil)

Index: setup.py
===================================================================

--- a/setup.py
+++ b/setup.py
@@ -8,10 +8,6 @@

 execfile(os.path.join('trytond', 'version.py'))

-SIMPLEJSON = []
-if sys.version_info < (2, 6):
-    SIMPLEJSON = ['simplejson']
-
 def read(fname):
     return open(os.path.join(os.path.dirname(__file__), fname)).read()

@@ -52,7 +48,6 @@
         'Natural Language :: Russian',
         'Natural Language :: Spanish',
         'Operating System :: OS Independent',
-        'Programming Language :: Python :: 2.5',
         'Programming Language :: Python :: 2.6',
         'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Application Frameworks',
@@ -63,7 +58,7 @@
         'relatorio >= 0.2.0',
         'Genshi',
         'python-dateutil',
-    ] + SIMPLEJSON,
+    ],
     extras_require={
         'PostgreSQL': ['psycopg2 >= 2.0'],
         'MySQL': ['MySQL-python'],

Index: trytond/backend/sqlite/database.py
===================================================================

--- a/trytond/backend/sqlite/database.py
+++ b/trytond/backend/sqlite/database.py
@@ -9,6 +9,7 @@
 from decimal import Decimal
 import datetime
 import time
+import sys

 _FIX_ROWCOUNT = False
 try:
@@ -357,7 +358,10 @@
         return select

 sqlite.register_converter('NUMERIC', lambda val: Decimal(val))
-sqlite.register_adapter(Decimal, lambda val: buffer(str(val)))
+if sys.version_info[0] == 2:
+    sqlite.register_adapter(Decimal, lambda val: buffer(str(val)))
+else:
+    sqlite.register_adapter(Decimal, lambda val: bytes(str(val)))
 sqlite.register_adapter(Session, int)
 def adapt_datetime(val):
     return val.replace(tzinfo=None).isoformat(" ")

Index: trytond/backend/sqlite/table.py
===================================================================

--- a/trytond/backend/sqlite/table.py
+++ b/trytond/backend/sqlite/table.py
@@ -127,7 +127,7 @@
             match = re.match(r'(\w+)(\((.*?)\))?', type_)
             if match:
                 typname = match.group(1).upper()
-                size = match.group(3) and int(match.group(3)) or None
+                size = match.group(3) and int(match.group(3)) or 0
             else:
                 typname = type_.upper()
                 size = -1

Index: trytond/ir/translation.py
===================================================================

--- a/trytond/ir/translation.py
+++ b/trytond/ir/translation.py
@@ -17,6 +17,7 @@
     from hashlib import md5
 except ImportError:
     from md5 import md5
+from functools import reduce
 from trytond.model import ModelView, ModelSQL, fields
 from trytond.model.cacheable import Cacheable
 from trytond.wizard import Wizard

Index: trytond/model/fields/one2many.py
===================================================================

--- a/trytond/model/fields/one2many.py
+++ b/trytond/model/fields/one2many.py
@@ -96,7 +96,7 @@

index_of_ids2 = dict((i, index) for index, i in enumerate(chain(*ids2)))
         for val in res.values():
-            val.sort(lambda x, y: cmp(index_of_ids2[x], index_of_ids2[y]))
+            val.sort(key=lambda x: index_of_ids2[x])
         return res

     def set(self, ids, model, name, values):

Index: trytond/model/model.py
===================================================================

--- a/trytond/model/model.py
+++ b/trytond/model/model.py
@@ -2,6 +2,7 @@
 #this repository contains the full copyright notices and license terms.

 import copy
+import collections
 from trytond.model import fields
 from trytond.error import WarningErrorMixin
 from trytond.pool import Pool
@@ -54,7 +55,7 @@
         fields_names += self._inherit_fields.keys()
         for field_name in fields_names:
default_method = getattr(self, 'default_%s' % field_name, False)
-            if callable(default_method):
+            if isinstance(default_method, collections.Callable):
                 res[field_name] = default_method
         self.__defaults = res
         return res
@@ -98,15 +99,17 @@
for attribute in ('on_change', 'on_change_with', 'autocomplete'):
                 function_name = '%s_%s' % (attribute, field_name)
                 if (getattr(field, attribute, False)
-                        and callable(getattr(self, function_name, False))):
+                        and isinstance(getattr(self, function_name, False),
+                            collections.Callable)):
                     self._rpc.setdefault(function_name, False)

     def __getattr__(self, name):
         # Search if a function exists in inherits parents
         for model_name, field_name in self._inherits.iteritems():
             model_obj = self.pool.get(model_name)
-            if hasattr(model_obj, name) and \
-                    callable(getattr(model_obj, name)):
+            if (hasattr(model_obj, name)
+                    and isinstance(getattr(model_obj, name),
+                        collections.Callable)):
                 return getattr(model_obj, name)
         raise AttributeError(name)


Index: trytond/model/modelsql.py
===================================================================

--- a/trytond/model/modelsql.py
+++ b/trytond/model/modelsql.py
@@ -4,6 +4,7 @@
 import contextlib
 import datetime
 import re
+from functools import reduce
 from decimal import Decimal
 from itertools import islice
 from trytond.model import ModelStorage
@@ -759,7 +760,7 @@
                     cursor.execute("SELECT id " \
                             'FROM "' + self._table + '" ' \
                             'WHERE ' + ' OR '.join(
-                                (clause,) * (len(args)/2)), args)
+                                (clause,) * (len(args) // 2)), args)
                     if cursor.fetchone():
                         raise Exception('ConcurrencyException',
                                 'Records were modified in the meanwhile')

Index: trytond/model/modelstorage.py
===================================================================

--- a/trytond/model/modelstorage.py
+++ b/trytond/model/modelstorage.py
@@ -12,6 +12,9 @@
 except ImportError:
     import StringIO
 import csv
+from functools import reduce
+import traceback
+import sys
 from trytond.model import Model
 from trytond.model import fields
 from trytond.model.browse import BrowseRecordList, BrowseRecord, \
@@ -841,7 +844,9 @@
                 logger.error(exp)
                 # XXX should raise Exception
                 Transaction().cursor.rollback()
-                warning = '\n'.join(map(str, exp[1:]) + [warning])
+                tb_s = reduce(lambda x, y: x + y,
+                        traceback.format_exception(*sys.exc_info()))
+                warning = '%s\n%s' % (tb_s, warning)
                 return (-1, res, exp, warning)
             done += 1
         return (done, 0, 0, 0)

Index: trytond/model/modelview.py
===================================================================

--- a/trytond/model/modelview.py
+++ b/trytond/model/modelview.py
@@ -167,9 +167,8 @@
             raise_p = False
             while True:
                 try:
-                    sql_inherit.sort(lambda x, y: \
-                            cmp(self._modules_list.index(x[2] or None),
-                                self._modules_list.index(y[2] or None)))
+                    sql_inherit.sort(key=lambda x:
+                        self._modules_list.index(x[2] or None))
                     break
                 except ValueError:
                     if raise_p:

Index: trytond/modules/__init__.py
===================================================================

--- a/trytond/modules/__init__.py
+++ b/trytond/modules/__init__.py
@@ -6,6 +6,9 @@
 import traceback
 import logging
 import contextlib
+from functools import reduce
+import imp
+import operator
 from trytond.backend import Database
 import trytond.tools as tools
 from trytond.config import CONFIG
@@ -91,7 +94,7 @@
         for attr in ('init', 'update'):
             if hasattr(self, attr):
                 setattr(node, attr, True)
-        self.childs.sort(lambda x, y: cmp(x.name, y.name))
+        self.childs.sort(key=operator.attrgetter('name'))

     def all_childs(self):
         res = []
@@ -334,7 +337,7 @@
                 if i.startswith(module) \
                         and i != module:
                     del sys.modules[i]
-            reload(sys.modules[module])
+            imp.reload(sys.modules[module])

     logger = logging.getLogger('modules')

@@ -352,7 +355,7 @@
                         and i != 'trytond.modules.' + module \
and getattr(sys.modules[i], '_TRYTON_RELOAD', True):
                     del sys.modules[i]
-            reload(sys.modules['trytond.modules.' + module])
+            imp.reload(sys.modules['trytond.modules.' + module])
             continue

         if os.path.isdir(OPJ(MODULES_PATH, module)):

Index: trytond/protocols/datatype.py
===================================================================

--- a/trytond/protocols/datatype.py
+++ b/trytond/protocols/datatype.py
@@ -55,6 +55,9 @@
             return self.decimal.__eq__(other)
         return super(Float, self).__eq__(other)

+    def __hash__(self):
+        return super(Float, self).__hash__()
+
     def __floordiv__(self, other, context=None):
         if isinstance(other, Decimal):
             return self.decimal.__floordiv__(other, context=context)

Index: trytond/pyson.py
===================================================================

--- a/trytond/pyson.py
+++ b/trytond/pyson.py
@@ -6,6 +6,7 @@
 else:
     import json
 import datetime
+from functools import reduce


 class PYSON(object):
@@ -405,7 +406,7 @@
             date = date.replace(year=year)
         if dct['dM']:
             month = date.month + dct['dM']
-            year = date.year + month / 12
+            year = date.year + month // 12
             month = month % 12
             date = date.replace(year=year, month=month)
         if dct['dd']:

Index: trytond/security.py
===================================================================

--- a/trytond/security.py
+++ b/trytond/security.py
@@ -41,7 +41,7 @@

 def logout(dbname, user, session):
     name = ''
-    if _USER_CACHE.get(dbname, {}).has_key(user):
+    if user in _USER_CACHE.get(dbname, {}):
         for i, real_session \
                 in enumerate(_USER_CACHE[dbname][user]):
             if real_session.session == session:
@@ -62,7 +62,7 @@
     result = None
     now = time.time()
     timeout = int(CONFIG['session_timeout'])
-    if _USER_CACHE.get(dbname, {}).has_key(user):
+    if user in _USER_CACHE.get(dbname, {}):
         to_del = []
         for i, real_session \
                 in enumerate(_USER_CACHE[dbname][user]):
@@ -81,7 +81,7 @@
     res = 0
     now = time.time()
     timeout = int(CONFIG['session_timeout'])
-    if _USER_CACHE.get(dbname, {}).has_key(int(user)):
+    if int(user) in _USER_CACHE.get(dbname, {}):
         for _, session in enumerate(_USER_CACHE[dbname][int(user)]):
             if abs(session.timestamp - now) < timeout:
                 res += 1

Index: trytond/tests/test_mptt.py
===================================================================

--- a/trytond/tests/test_mptt.py
+++ b/trytond/tests/test_mptt.py
@@ -23,8 +23,7 @@
             ('parent', '=', parent_id),
             ])
         childs = self.mptt.read(child_ids, ['left', 'right'])
-        childs.sort(lambda x, y: cmp(child_ids.index(x['id']),
-            child_ids.index(y['id'])))
+        childs.sort(key=lambda x: child_ids.index(x['id']))
         for child in childs:
             assert child['left'] > left, \
                     'Record (%d): left %d <= parent left %d' % \
@@ -152,7 +151,7 @@

         with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
             record_ids = self.mptt.search([])
-            self.mptt.write(record_ids[:len(record_ids)/2], {
+            self.mptt.write(record_ids[:len(record_ids) // 2], {
                     'active': False
                     })
             self.CheckTree()
@@ -186,7 +185,7 @@

         with Transaction().start(DB_NAME, USER, CONTEXT) as transaction:
             record_ids = self.mptt.search([])
-            self.mptt.delete(record_ids[:len(record_ids)/2])
+            self.mptt.delete(record_ids[:len(record_ids) // 2])
             self.CheckTree()

             transaction.cursor.rollback()

Index: trytond/tests/test_tryton.py
===================================================================

--- a/trytond/tests/test_tryton.py
+++ b/trytond/tests/test_tryton.py
@@ -11,13 +11,6 @@
 if os.path.isdir(DIR):
     sys.path.insert(0, os.path.dirname(DIR))

-if sys.version_info[:2] <= (2, 5):
-    # ugly monkeypatch to make doctests work. For the reasons see
-    # http://mail.python.org/pipermail/python-dev/2008-July/081420.html
-    # It can go away once we drop Python 2.5
-    import decimal
-    decimal.Decimal.__repr__ = lambda s: "Decimal('%s')" % str(s)
-
 import unittest
 import doctest
 from lxml import etree



--
[email protected] mailing list

Reply via email to