27d80112bf93d3d782bb1b5ced6f8ca7bd7285a3
[sdc/sdc-distribution-client.git] /
1 """Utilities for writing code that runs on Python 2 and 3"""
2
3 #Copyright (c) 2010-2011 Benjamin Peterson
4
5 #Permission is hereby granted, free of charge, to any person obtaining a copy of
6 #this software and associated documentation files (the "Software"), to deal in
7 #the Software without restriction, including without limitation the rights to
8 #use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 #the Software, and to permit persons to whom the Software is furnished to do so,
10 #subject to the following conditions:
11
12 #The above copyright notice and this permission notice shall be included in all
13 #copies or substantial portions of the Software.
14
15 #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 #FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 #COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 #IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 #CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 import operator
23 import sys
24 import types
25
26 __author__ = "Benjamin Peterson <benjamin@python.org>"
27 __version__ = "1.2.0"  # Revision 41c74fef2ded
28
29
30 # True if we are running on Python 3.
31 PY3 = sys.version_info[0] == 3
32
33 if PY3:
34     string_types = str,
35     integer_types = int,
36     class_types = type,
37     text_type = str
38     binary_type = bytes
39
40     MAXSIZE = sys.maxsize
41 else:
42     string_types = basestring,
43     integer_types = (int, long)
44     class_types = (type, types.ClassType)
45     text_type = unicode
46     binary_type = str
47
48     if sys.platform.startswith("java"):
49         # Jython always uses 32 bits.
50         MAXSIZE = int((1 << 31) - 1)
51     else:
52         # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
53         class X(object):
54             def __len__(self):
55                 return 1 << 31
56         try:
57             len(X())
58         except OverflowError:
59             # 32-bit
60             MAXSIZE = int((1 << 31) - 1)
61         else:
62             # 64-bit
63             MAXSIZE = int((1 << 63) - 1)
64             del X
65
66
67 def _add_doc(func, doc):
68     """Add documentation to a function."""
69     func.__doc__ = doc
70
71
72 def _import_module(name):
73     """Import module, returning the module after the last dot."""
74     __import__(name)
75     return sys.modules[name]
76
77
78 class _LazyDescr(object):
79
80     def __init__(self, name):
81         self.name = name
82
83     def __get__(self, obj, tp):
84         result = self._resolve()
85         setattr(obj, self.name, result)
86         # This is a bit ugly, but it avoids running this again.
87         delattr(tp, self.name)
88         return result
89
90
91 class MovedModule(_LazyDescr):
92
93     def __init__(self, name, old, new=None):
94         super(MovedModule, self).__init__(name)
95         if PY3:
96             if new is None:
97                 new = name
98             self.mod = new
99         else:
100             self.mod = old
101
102     def _resolve(self):
103         return _import_module(self.mod)
104
105
106 class MovedAttribute(_LazyDescr):
107
108     def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
109         super(MovedAttribute, self).__init__(name)
110         if PY3:
111             if new_mod is None:
112                 new_mod = name
113             self.mod = new_mod
114             if new_attr is None:
115                 if old_attr is None:
116                     new_attr = name
117                 else:
118                     new_attr = old_attr
119             self.attr = new_attr
120         else:
121             self.mod = old_mod
122             if old_attr is None:
123                 old_attr = name
124             self.attr = old_attr
125
126     def _resolve(self):
127         module = _import_module(self.mod)
128         return getattr(module, self.attr)
129
130
131
132 class _MovedItems(types.ModuleType):
133     """Lazy loading of moved objects"""
134
135
136 _moved_attributes = [
137     MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
138     MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
139     MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
140     MovedAttribute("map", "itertools", "builtins", "imap", "map"),
141     MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
142     MovedAttribute("reduce", "__builtin__", "functools"),
143     MovedAttribute("StringIO", "StringIO", "io"),
144     MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
145     MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
146
147     MovedModule("builtins", "__builtin__"),
148     MovedModule("configparser", "ConfigParser"),
149     MovedModule("copyreg", "copy_reg"),
150     MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
151     MovedModule("http_cookies", "Cookie", "http.cookies"),
152     MovedModule("html_entities", "htmlentitydefs", "html.entities"),
153     MovedModule("html_parser", "HTMLParser", "html.parser"),
154     MovedModule("http_client", "httplib", "http.client"),
155     MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
156     MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
157     MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
158     MovedModule("cPickle", "cPickle", "pickle"),
159     MovedModule("queue", "Queue"),
160     MovedModule("reprlib", "repr"),
161     MovedModule("socketserver", "SocketServer"),
162     MovedModule("tkinter", "Tkinter"),
163     MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
164     MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
165     MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
166     MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
167     MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
168     MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
169     MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
170     MovedModule("tkinter_colorchooser", "tkColorChooser",
171                 "tkinter.colorchooser"),
172     MovedModule("tkinter_commondialog", "tkCommonDialog",
173                 "tkinter.commondialog"),
174     MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
175     MovedModule("tkinter_font", "tkFont", "tkinter.font"),
176     MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
177     MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
178                 "tkinter.simpledialog"),
179     MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
180     MovedModule("winreg", "_winreg"),
181 ]
182 for attr in _moved_attributes:
183     setattr(_MovedItems, attr.name, attr)
184 del attr
185
186 moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")
187
188
189 def add_move(move):
190     """Add an item to six.moves."""
191     setattr(_MovedItems, move.name, move)
192
193
194 def remove_move(name):
195     """Remove item from six.moves."""
196     try:
197         delattr(_MovedItems, name)
198     except AttributeError:
199         try:
200             del moves.__dict__[name]
201         except KeyError:
202             raise AttributeError("no such move, %r" % (name,))
203
204
205 if PY3:
206     _meth_func = "__func__"
207     _meth_self = "__self__"
208
209     _func_code = "__code__"
210     _func_defaults = "__defaults__"
211
212     _iterkeys = "keys"
213     _itervalues = "values"
214     _iteritems = "items"
215 else:
216     _meth_func = "im_func"
217     _meth_self = "im_self"
218
219     _func_code = "func_code"
220     _func_defaults = "func_defaults"
221
222     _iterkeys = "iterkeys"
223     _itervalues = "itervalues"
224     _iteritems = "iteritems"
225
226
227 try:
228     advance_iterator = next
229 except NameError:
230     def advance_iterator(it):
231         return it.next()
232 next = advance_iterator
233
234
235 if PY3:
236     def get_unbound_function(unbound):
237         return unbound
238
239     Iterator = object
240
241     def callable(obj):
242         return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
243 else:
244     def get_unbound_function(unbound):
245         return unbound.im_func
246
247     class Iterator(object):
248
249         def next(self):
250             return type(self).__next__(self)
251
252     callable = callable
253 _add_doc(get_unbound_function,
254          """Get the function out of a possibly unbound function""")
255
256
257 get_method_function = operator.attrgetter(_meth_func)
258 get_method_self = operator.attrgetter(_meth_self)
259 get_function_code = operator.attrgetter(_func_code)
260 get_function_defaults = operator.attrgetter(_func_defaults)
261
262
263 def iterkeys(d):
264     """Return an iterator over the keys of a dictionary."""
265     return iter(getattr(d, _iterkeys)())
266
267 def itervalues(d):
268     """Return an iterator over the values of a dictionary."""
269     return iter(getattr(d, _itervalues)())
270
271 def iteritems(d):
272     """Return an iterator over the (key, value) pairs of a dictionary."""
273     return iter(getattr(d, _iteritems)())
274
275
276 if PY3:
277     def b(s):
278         return s.encode("latin-1")
279     def u(s):
280         return s
281     if sys.version_info[1] <= 1:
282         def int2byte(i):
283             return bytes((i,))
284     else:
285         # This is about 2x faster than the implementation above on 3.2+
286         int2byte = operator.methodcaller("to_bytes", 1, "big")
287     import io
288     StringIO = io.StringIO
289     BytesIO = io.BytesIO
290 else:
291     def b(s):
292         return s
293     def u(s):
294         return unicode(s, "unicode_escape")
295     int2byte = chr
296     import StringIO
297     StringIO = BytesIO = StringIO.StringIO
298 _add_doc(b, """Byte literal""")
299 _add_doc(u, """Text literal""")
300
301
302 if PY3:
303     import builtins
304     exec_ = getattr(builtins, "exec")
305
306
307     def reraise(tp, value, tb=None):
308         if value.__traceback__ is not tb:
309             raise value.with_traceback(tb)
310         raise value
311
312
313     print_ = getattr(builtins, "print")
314     del builtins
315
316 else:
317     def exec_(code, globs=None, locs=None):
318         """Execute code in a namespace."""
319         if globs is None:
320             frame = sys._getframe(1)
321             globs = frame.f_globals
322             if locs is None:
323                 locs = frame.f_locals
324             del frame
325         elif locs is None:
326             locs = globs
327         exec("""exec code in globs, locs""")
328
329
330     exec_("""def reraise(tp, value, tb=None):
331     raise tp, value, tb
332 """)
333
334
335     def print_(*args, **kwargs):
336         """The new-style print function."""
337         fp = kwargs.pop("file", sys.stdout)
338         if fp is None:
339             return
340         def write(data):
341             if not isinstance(data, basestring):
342                 data = str(data)
343             fp.write(data)
344         want_unicode = False
345         sep = kwargs.pop("sep", None)
346         if sep is not None:
347             if isinstance(sep, unicode):
348                 want_unicode = True
349             elif not isinstance(sep, str):
350                 raise TypeError("sep must be None or a string")
351         end = kwargs.pop("end", None)
352         if end is not None:
353             if isinstance(end, unicode):
354                 want_unicode = True
355             elif not isinstance(end, str):
356                 raise TypeError("end must be None or a string")
357         if kwargs:
358             raise TypeError("invalid keyword arguments to print()")
359         if not want_unicode:
360             for arg in args:
361                 if isinstance(arg, unicode):
362                     want_unicode = True
363                     break
364         if want_unicode:
365             newline = unicode("\n")
366             space = unicode(" ")
367         else:
368             newline = "\n"
369             space = " "
370         if sep is None:
371             sep = space
372         if end is None:
373             end = newline
374         for i, arg in enumerate(args):
375             if i:
376                 write(sep)
377             write(arg)
378         write(end)
379
380 _add_doc(reraise, """Reraise an exception.""")
381
382
383 def with_metaclass(meta, base=object):
384     """Create a base class with a metaclass."""
385     return meta("NewBase", (base,), {})