064415ecfa5fab16bf478e053123a1cb08bd9d19
[scons.git] / src / engine / SCons / compat / builtins.py
1 #
2 # __COPYRIGHT__
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject to
10 # the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
16 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
17 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 #
23
24 # Portions of the following are derived from the compat.py file in
25 # Twisted, under the following copyright:
26 #
27 # Copyright (c) 2001-2004 Twisted Matrix Laboratories
28
29 __doc__ = """
30 Compatibility idioms for __builtin__ names
31
32 This module adds names to the __builtin__ module for things that we want
33 to use in SCons but which don't show up until later Python versions than
34 the earliest ones we support.
35
36 This module checks for the following __builtin__ names:
37
38         all()
39         any()
40         bool()
41         dict()
42         sorted()
43         True
44         False
45         zip()
46
47 Implementations of functions are *NOT* guaranteed to be fully compliant
48 with these functions in later versions of Python.  We are only concerned
49 with adding functionality that we actually use in SCons, so be wary
50 if you lift this code for other uses.  (That said, making these more
51 nearly the same as later, official versions is still a desirable goal,
52 we just don't need to be obsessive about it.)
53
54 If you're looking at this with pydoc and various names don't show up in
55 the FUNCTIONS or DATA output, that means those names are already built in
56 to this version of Python and we don't need to add them from this module.
57 """
58
59 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
60
61 import __builtin__
62
63 try:
64     all
65 except NameError:
66     # Pre-2.5 Python has no all() function.
67     def all(iterable):
68         """
69         Returns True if all elements of the iterable are true.
70         """
71         for element in iterable:
72             if not element:
73                 return False
74         return True
75     __builtin__.all = all
76     all = all
77
78 try:
79     any
80 except NameError:
81     # Pre-2.5 Python has no any() function.
82     def any(iterable):
83         """
84         Returns True if any element of the iterable is true.
85         """
86         for element in iterable:
87             if element:
88                 return True
89         return False
90     __builtin__.any = any
91     any = any
92
93 try:
94     bool
95 except NameError:
96     # Pre-2.2 Python has no bool() function.
97     def bool(value):
98         """Demote a value to 0 or 1, depending on its truth value.
99
100         This is not to be confused with types.BooleanType, which is
101         way too hard to duplicate in early Python versions to be
102         worth the trouble.
103         """
104         return not not value
105     __builtin__.bool = bool
106     bool = bool
107
108 try:
109     dict
110 except NameError:
111     # Pre-2.2 Python has no dict() keyword.
112     def dict(seq=[], **kwargs):
113         """
114         New dictionary initialization.
115         """
116         d = {}
117         for k, v in seq:
118             d[k] = v
119         d.update(kwargs)
120         return d
121     __builtin__.dict = dict
122
123 try:
124     False
125 except NameError:
126     # Pre-2.2 Python has no False keyword.
127     __builtin__.False = not 1
128     # Assign to False in this module namespace so it shows up in pydoc output.
129     False = False
130
131 try:
132     True
133 except NameError:
134     # Pre-2.2 Python has no True keyword.
135     __builtin__.True = not 0
136     # Assign to True in this module namespace so it shows up in pydoc output.
137     True = True
138
139 try:
140     file
141 except NameError:
142     # Pre-2.2 Python has no file() function.
143     __builtin__.file = open
144
145 try:
146     sorted
147 except NameError:
148     # Pre-2.4 Python has no sorted() function.
149     #
150     # The pre-2.4 Python list.sort() method does not support
151     # list.sort(key=) nor list.sort(reverse=) keyword arguments, so
152     # we must implement the functionality of those keyword arguments
153     # by hand instead of passing them to list.sort().
154     def sorted(iterable, cmp=None, key=None, reverse=False):
155         if key:
156             decorated = [ (key(x), x) for x in iterable ]
157             if cmp is None:
158                 # Pre-2.3 Python does not support list.sort(None).
159                 decorated.sort()
160             else:
161                 decorated.sort(cmp)
162             if reverse:
163                 decorated.reverse()
164             result = [ t[1] for t in decorated ]
165         else:
166             result = iterable[:]
167             if cmp is None:
168                 # Pre-2.3 Python does not support list.sort(None).
169                 result.sort()
170             else:
171                 result.sort(cmp)
172             if reverse:
173                 result.reverse()
174         return result
175     __builtin__.sorted = sorted
176
177 #
178 try:
179     zip
180 except NameError:
181     # Pre-2.2 Python has no zip() function.
182     def zip(*lists):
183         """
184         Emulates the behavior we need from the built-in zip() function
185         added in Python 2.2.
186
187         Returns a list of tuples, where each tuple contains the i-th
188         element rom each of the argument sequences.  The returned
189         list is truncated in length to the length of the shortest
190         argument sequence.
191         """
192         result = []
193         for i in xrange(min(map(len, lists))):
194             result.append(tuple(map(lambda l: l[i], lists)))
195         return result
196     __builtin__.zip = zip
197
198
199
200 #if sys.version_info[:3] in ((2, 2, 0), (2, 2, 1)):
201 #    def lstrip(s, c=string.whitespace):
202 #        while s and s[0] in c:
203 #            s = s[1:]
204 #        return s
205 #    def rstrip(s, c=string.whitespace):
206 #        while s and s[-1] in c:
207 #            s = s[:-1]
208 #        return s
209 #    def strip(s, c=string.whitespace, l=lstrip, r=rstrip):
210 #        return l(r(s, c), c)
211 #
212 #    object.__setattr__(str, 'lstrip', lstrip)
213 #    object.__setattr__(str, 'rstrip', rstrip)
214 #    object.__setattr__(str, 'strip', strip)
215
216 # Local Variables:
217 # tab-width:4
218 # indent-tabs-mode:nil
219 # End:
220 # vim: set expandtab tabstop=4 shiftwidth=4: