Imported Upstream version 0.2.1a
[debian_python-primes.git] / src / pyprimes / compat23.py
blob70c1dac8865ed187be4a6d0725405232427b0f93
1 # -*- coding: utf-8 -*-
3 ## Part of the pyprimes.py package.
4 ##
5 ## Copyright © 2014 Steven D'Aprano.
6 ## See the file __init__.py for the licence terms for this software.
9 """Python 2 and 3 compatibility layer for the pyprimes package.
11 This module is considered a private implementation detail and is subject
12 to change without notice.
13 """
15 from __future__ import division
18 try:
19 import builtins # Python 3.x.
20 except ImportError:
21 # We're probably running Python 2.x.
22 import __builtin__ as builtins
25 try:
26 next = builtins.next
27 except AttributeError:
28 # No next() builtin, so we're probably running Python 2.4 or 2.5.
29 def next(iterator, *args):
30 if len(args) > 1:
31 n = len(args) + 1
32 raise TypeError("next expected at most 2 arguments, got %d" % n)
33 try:
34 return iterator.next()
35 except StopIteration:
36 if args:
37 return args[0]
38 else:
39 raise
42 try:
43 range = builtins.xrange
44 except AttributeError:
45 # No xrange built-in, so we're probably running Python3
46 # where range is already a lazy iterator.
47 assert type(builtins.range(3)) is not list
48 range = builtins.range
51 try:
52 from itertools import ifilter as filter, izip as zip
53 except ImportError:
54 # Python 3, where filter and zip are already lazy.
55 assert type(builtins.filter(None, [1, 2])) is not list
56 assert type(builtins.zip("ab", [1, 2])) is not list
57 filter = builtins.filter
58 zip = builtins.zip
61 try:
62 all = builtins.all
63 except AttributeError:
64 # Likely Python 2.4.
65 def all(iterable):
66 for element in iterable:
67 if not element:
68 return False
69 return True
72 try:
73 from itertools import compress
74 except ImportError:
75 # Must be Python 2.x, so we need to roll our own.
76 def compress(data, selectors):
77 """compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"""
78 return (d for d, s in zip(data, selectors) if s)
81 try:
82 reduce = builtins.reduce
83 except AttributeError:
84 from functools import reduce