diff options
author | Sylvain Th?nault <sylvain.thenault@logilab.fr> | 2010-10-11 15:58:50 +0200 |
---|---|---|
committer | Sylvain Th?nault <sylvain.thenault@logilab.fr> | 2010-10-11 15:58:50 +0200 |
commit | e2dd70f5874f476658523b1acf89cf003f21b43a (patch) | |
tree | 28f9e8759bb5b79c8427412bcf85f5f531c16acc | |
parent | 427ef35c33b99b137356525dedef3cb0f2f390cd (diff) | |
parent | bebe2ebbae9ba81b60a74e4b210576058ca3d8bd (diff) | |
download | logilab-common-e2dd70f5874f476658523b1acf89cf003f21b43a.tar.gz |
backport stable
-rw-r--r-- | compat.py | 157 | ||||
-rw-r--r-- | configuration.py | 11 | ||||
-rw-r--r-- | table.py | 2 | ||||
-rw-r--r-- | test/unittest_compat.py | 15 | ||||
-rw-r--r-- | testlib.py | 3 | ||||
-rw-r--r-- | textutils.py | 2 |
6 files changed, 30 insertions, 160 deletions
@@ -50,6 +50,7 @@ else: def str_encode(string, encoding): return str(string) +# XXX shouldn't we remove this and just let 2to3 do his job ? try: callable = callable except NameError:# callable removed from py3k @@ -77,154 +78,31 @@ try: except ImportError: import pickle -# Python 2.3 doesn't have `set` try: set = set frozenset = frozenset -except NameError: - try: - from sets import Set as set, ImmutableSet as frozenset - except ImportError: - class _baseset(object): - def __init__(self, values=()): - self._data = {} - warn("This implementation of Set is not complete !", - stacklevel=2) - for v in values: - self._data[v] = 1 - - def __or__(self, other): - result = self.__class__(self._data.keys()) - for val in other: - result.add(val) - return result - __add__ = __or__ - - def __and__(self, other): - result = self.__class__() - for val in other: - if val in self._data: - result.add(val) - return result - - def __sub__(self, other): - result = self.__class__(self._data.keys()) - for val in other: - if val in self._data: - result.remove(val) - return result - - def __cmp__(self, other): - keys = self._data.keys() - okeys = other._data.keys() - keys.sort() - okeys.sort() - return cmp(keys, okeys) - - def __len__(self): - return len(self._data) - - def __repr__(self): - elements = self._data.keys() - return 'lcc.%s(%r)' % (self.__class__.__name__, elements) - __str__ = __repr__ - - def __iter__(self): - return iter(self._data) - - class frozenset(_baseset): - """immutable set (can be set in dictionaries)""" - def __init__(self, values=()): - super(frozenset, self).__init__(values) - self._hashcode = None - - def _compute_hash(self): - """taken from python stdlib (sets.py)""" - # Calculate hash code for a set by xor'ing the hash codes of - # the elements. This ensures that the hash code does not depend - # on the order in which elements are added to the set. This is - # not called __hash__ because a BaseSet should not be hashable; - # only an ImmutableSet is hashable. - result = 0 - for elt in self: - result ^= hash(elt) - return result - - def __hash__(self): - """taken from python stdlib (sets.py)""" - if self._hashcode is None: - self._hashcode = self._compute_hash() - return self._hashcode - - - class set(_baseset): - """mutable set""" - def add(self, value): - self._data[value] = 1 - - def remove(self, element): - """removes <element> from set""" - del self._data[element] - - def pop(self): - """pops an arbitrary element from set""" - return self._data.popitem()[0] - - def __hash__(self): - """mutable set cannot be hashed.""" - raise TypeError("set objects are not hashable") - - del _baseset # don't explicitly provide this class +except NameError:# Python 2.3 doesn't have `set` + from sets import Set as set, ImmutableSet as frozenset + +from logilab.common.deprecation import deprecated + +from itertools import izip, chain, imap +izip = deprecated('izip exists in itertools since py2.3')(izip) +imap = deprecated('imap exists in itertools since py2.3')(imap) +chain = deprecated('chain exists in itertools since py2.3')(chain) + +sum = deprecated('sum exists in __builtins since py2.3')(sum) +enumerate = deprecated('enumerate exists in __builtins since py2.3')(enumerate) -try: - from itertools import izip, chain, imap -except ImportError: - # from itertools documentation ### - def izip(*iterables): - iterables = map(iter, iterables) - while iterables: - result = [i.next() for i in iterables] - yield tuple(result) - - def chain(*iterables): - for it in iterables: - for element in it: - yield element - - def imap(function, *iterables): - iterables = map(iter, iterables) - while True: - args = [i.next() for i in iterables] - if function is None: - yield tuple(args) - else: - yield function(*args) -try: - sum = sum - enumerate = enumerate -except NameError: - # define the sum and enumerate functions (builtins introduced in py 2.3) - import operator - def sum(seq, start=0): - """Returns the sum of all elements in the sequence""" - return reduce(operator.add, seq, start) - - def enumerate(iterable): - """emulates the python2.3 enumerate() function""" - i = 0 - for val in iterable: - yield i, val - i += 1 - #return zip(range(len(iterable)), iterable) try: sorted = sorted reversed = reversed -except NameError: +except NameError: # py2.3 def sorted(iterable, cmp=None, key=None, reverse=False): original = list(iterable) if key: - l2 = [(key(elt), index) for index, elt in enumerate(original)] + l2 = [(key(elt), index) for index, elt in builtins.enumerate(original)] else: l2 = original l2.sort(cmp) @@ -239,9 +117,9 @@ except NameError: l2.reverse() return l2 -try: # +try: max = max - max(("ab","cde"),key=len) + max(("ab","cde"),key=len) # does not work in py2.3 except TypeError: def max( *args, **kargs): if len(args) == 0: @@ -386,6 +264,7 @@ else: obj.__init__(*args, **kwargs) return obj +# XXX shouldn't we remove this and just let 2to3 do his job ? # range or xrange? try: range = xrange diff --git a/configuration.py b/configuration.py index ee79bbb..4006813 100644 --- a/configuration.py +++ b/configuration.py @@ -119,6 +119,8 @@ from logilab.common.compat import str_encode as _encode from logilab.common.textutils import normalize_text, unquote from logilab.common import optik_ext as optparse +OptionError = optparse.OptionError + REQUIRED = [] class UnsupportedAction(Exception): @@ -359,6 +361,10 @@ def ini_format_section(stream, section, options, encoding=None, doc=None): if doc: print >> stream, _encode(comment(doc), encoding) print >> stream, '[%s]' % section + ini_format(stream, options, encoding) + +def ini_format(stream, options, encoding): + """format options using the INI format""" for optname, optdict, value in options: value = format_option_value(optdict, value) help = optdict.get('help') @@ -852,7 +858,8 @@ class OptionsProviderMixIn(object): for option in self.options: if option[0] == opt: return option[1] - raise optparse.OptionError('no such option in section %r' % self.name, opt) + raise OptionError('no such option %s in section %r' + % (self.name, opt), opt) def all_options(self): @@ -937,7 +944,7 @@ class ConfigurationMixIn(OptionsManagerMixIn, OptionsProviderMixIn): def get(self, key, default=None): try: return getattr(self.config, self.option_name(key)) - except (optparse.OptionError, AttributeError): + except (OptionError, AttributeError): return default @@ -18,7 +18,7 @@ """Table management module.""" __docformat__ = "restructuredtext en" -from logilab.common.compat import enumerate, sum, set +from logilab.common.compat import set class Table(object): """Table defines a data table with column and row names. diff --git a/test/unittest_compat.py b/test/unittest_compat.py index ec566b0..90b8994 100644 --- a/test/unittest_compat.py +++ b/test/unittest_compat.py @@ -83,25 +83,10 @@ class CompatTCMixIn: class Py23CompatTC(CompatTCMixIn, TestCase): - BUILTINS = ('enumerate', 'sum') MODNAMES = { 'sets' : ('Set', 'ImmutableSet'), - 'itertools' : ('izip', 'chain'), } - def test_sum(self): - if sys.version_info >= (3, 0): - self.skip("don't test 2.3 compat 'sum' on >= 3.0") - from logilab.common.compat import sum - self.assertEqual(sum(range(5)), 10) - self.assertRaises(TypeError, sum, 'abc') - - def test_enumerate(self): - from logilab.common.compat import enumerate - self.assertEqual(list(enumerate([])), []) - self.assertEqual(list(enumerate('abc')), - [(0, 'a'), (1, 'b'), (2, 'c')]) - def test_basic_set(self): from logilab.common.compat import set s = set('abc') @@ -84,8 +84,7 @@ except ImportError: test_support = TestSupport() # pylint: disable=W0622 -from logilab.common.compat import (set, enumerate, any, sorted, InheritableSet, - callable) +from logilab.common.compat import set, any, sorted, InheritableSet, callable # pylint: enable-msg=W0622 from logilab.common.modutils import load_module_from_name from logilab.common.debugger import Debugger, colorize_source diff --git a/textutils.py b/textutils.py index f83b05c..9fb59bb 100644 --- a/textutils.py +++ b/textutils.py @@ -286,7 +286,7 @@ def text_to_dict(text): return res for line in text.splitlines(): line = line.strip() - if line: + if line and not line.startswith('#'): key, value = [w.strip() for w in line.split('=', 1)] if key in res: try: |