1420216e5SHanoh Haim"""Utilities for writing code that runs on Python 2 and 3"""
2420216e5SHanoh Haim
3420216e5SHanoh Haim# Copyright (c) 2010-2015 Benjamin Peterson
4420216e5SHanoh Haim#
5420216e5SHanoh Haim# Permission is hereby granted, free of charge, to any person obtaining a copy
6420216e5SHanoh Haim# of this software and associated documentation files (the "Software"), to deal
7420216e5SHanoh Haim# in the Software without restriction, including without limitation the rights
8420216e5SHanoh Haim# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9420216e5SHanoh Haim# copies of the Software, and to permit persons to whom the Software is
10420216e5SHanoh Haim# furnished to do so, subject to the following conditions:
11420216e5SHanoh Haim#
12420216e5SHanoh Haim# The above copyright notice and this permission notice shall be included in all
13420216e5SHanoh Haim# copies or substantial portions of the Software.
14420216e5SHanoh Haim#
15420216e5SHanoh Haim# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16420216e5SHanoh Haim# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17420216e5SHanoh Haim# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18420216e5SHanoh Haim# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19420216e5SHanoh Haim# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20420216e5SHanoh Haim# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21420216e5SHanoh Haim# SOFTWARE.
22420216e5SHanoh Haim
23420216e5SHanoh Haimfrom __future__ import absolute_import
24420216e5SHanoh Haim
25420216e5SHanoh Haimimport functools
26420216e5SHanoh Haimimport itertools
27420216e5SHanoh Haimimport operator
28420216e5SHanoh Haimimport sys
29420216e5SHanoh Haimimport types
30420216e5SHanoh Haim
31420216e5SHanoh Haim__author__ = "Benjamin Peterson <benjamin@python.org>"
32420216e5SHanoh Haim__version__ = "1.10.0"
33420216e5SHanoh Haim
34420216e5SHanoh Haim
35420216e5SHanoh Haim# Useful for very coarse version differentiation.
36420216e5SHanoh HaimPY2 = sys.version_info[0] == 2
37420216e5SHanoh HaimPY3 = sys.version_info[0] == 3
38420216e5SHanoh HaimPY34 = sys.version_info[0:2] >= (3, 4)
39420216e5SHanoh Haim
40420216e5SHanoh Haimif PY3:
41420216e5SHanoh Haim    string_types = str,
42420216e5SHanoh Haim    integer_types = int,
43420216e5SHanoh Haim    class_types = type,
44420216e5SHanoh Haim    text_type = str
45420216e5SHanoh Haim    binary_type = bytes
46420216e5SHanoh Haim
47420216e5SHanoh Haim    MAXSIZE = sys.maxsize
48420216e5SHanoh Haimelse:
49420216e5SHanoh Haim    string_types = basestring,
50420216e5SHanoh Haim    integer_types = (int, long)
51420216e5SHanoh Haim    class_types = (type, types.ClassType)
52420216e5SHanoh Haim    text_type = unicode
53420216e5SHanoh Haim    binary_type = str
54420216e5SHanoh Haim
55420216e5SHanoh Haim    if sys.platform.startswith("java"):
56420216e5SHanoh Haim        # Jython always uses 32 bits.
57420216e5SHanoh Haim        MAXSIZE = int((1 << 31) - 1)
58420216e5SHanoh Haim    else:
59420216e5SHanoh Haim        # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60420216e5SHanoh Haim        class X(object):
61420216e5SHanoh Haim
62420216e5SHanoh Haim            def __len__(self):
63420216e5SHanoh Haim                return 1 << 31
64420216e5SHanoh Haim        try:
65420216e5SHanoh Haim            len(X())
66420216e5SHanoh Haim        except OverflowError:
67420216e5SHanoh Haim            # 32-bit
68420216e5SHanoh Haim            MAXSIZE = int((1 << 31) - 1)
69420216e5SHanoh Haim        else:
70420216e5SHanoh Haim            # 64-bit
71420216e5SHanoh Haim            MAXSIZE = int((1 << 63) - 1)
72420216e5SHanoh Haim        del X
73420216e5SHanoh Haim
74420216e5SHanoh Haim
75420216e5SHanoh Haimdef _add_doc(func, doc):
76420216e5SHanoh Haim    """Add documentation to a function."""
77420216e5SHanoh Haim    func.__doc__ = doc
78420216e5SHanoh Haim
79420216e5SHanoh Haim
80420216e5SHanoh Haimdef _import_module(name):
81420216e5SHanoh Haim    """Import module, returning the module after the last dot."""
82420216e5SHanoh Haim    __import__(name)
83420216e5SHanoh Haim    return sys.modules[name]
84420216e5SHanoh Haim
85420216e5SHanoh Haim
86420216e5SHanoh Haimclass _LazyDescr(object):
87420216e5SHanoh Haim
88420216e5SHanoh Haim    def __init__(self, name):
89420216e5SHanoh Haim        self.name = name
90420216e5SHanoh Haim
91420216e5SHanoh Haim    def __get__(self, obj, tp):
92420216e5SHanoh Haim        result = self._resolve()
93420216e5SHanoh Haim        setattr(obj, self.name, result)  # Invokes __set__.
94420216e5SHanoh Haim        try:
95420216e5SHanoh Haim            # This is a bit ugly, but it avoids running this again by
96420216e5SHanoh Haim            # removing this descriptor.
97420216e5SHanoh Haim            delattr(obj.__class__, self.name)
98420216e5SHanoh Haim        except AttributeError:
99420216e5SHanoh Haim            pass
100420216e5SHanoh Haim        return result
101420216e5SHanoh Haim
102420216e5SHanoh Haim
103420216e5SHanoh Haimclass MovedModule(_LazyDescr):
104420216e5SHanoh Haim
105420216e5SHanoh Haim    def __init__(self, name, old, new=None):
106420216e5SHanoh Haim        super(MovedModule, self).__init__(name)
107420216e5SHanoh Haim        if PY3:
108420216e5SHanoh Haim            if new is None:
109420216e5SHanoh Haim                new = name
110420216e5SHanoh Haim            self.mod = new
111420216e5SHanoh Haim        else:
112420216e5SHanoh Haim            self.mod = old
113420216e5SHanoh Haim
114420216e5SHanoh Haim    def _resolve(self):
115420216e5SHanoh Haim        return _import_module(self.mod)
116420216e5SHanoh Haim
117420216e5SHanoh Haim    def __getattr__(self, attr):
118420216e5SHanoh Haim        _module = self._resolve()
119420216e5SHanoh Haim        value = getattr(_module, attr)
120420216e5SHanoh Haim        setattr(self, attr, value)
121420216e5SHanoh Haim        return value
122420216e5SHanoh Haim
123420216e5SHanoh Haim
124420216e5SHanoh Haimclass _LazyModule(types.ModuleType):
125420216e5SHanoh Haim
126420216e5SHanoh Haim    def __init__(self, name):
127420216e5SHanoh Haim        super(_LazyModule, self).__init__(name)
128420216e5SHanoh Haim        self.__doc__ = self.__class__.__doc__
129420216e5SHanoh Haim
130420216e5SHanoh Haim    def __dir__(self):
131420216e5SHanoh Haim        attrs = ["__doc__", "__name__"]
132420216e5SHanoh Haim        attrs += [attr.name for attr in self._moved_attributes]
133420216e5SHanoh Haim        return attrs
134420216e5SHanoh Haim
135420216e5SHanoh Haim    # Subclasses should override this
136420216e5SHanoh Haim    _moved_attributes = []
137420216e5SHanoh Haim
138420216e5SHanoh Haim
139420216e5SHanoh Haimclass MovedAttribute(_LazyDescr):
140420216e5SHanoh Haim
141420216e5SHanoh Haim    def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
142420216e5SHanoh Haim        super(MovedAttribute, self).__init__(name)
143420216e5SHanoh Haim        if PY3:
144420216e5SHanoh Haim            if new_mod is None:
145420216e5SHanoh Haim                new_mod = name
146420216e5SHanoh Haim            self.mod = new_mod
147420216e5SHanoh Haim            if new_attr is None:
148420216e5SHanoh Haim                if old_attr is None:
149420216e5SHanoh Haim                    new_attr = name
150420216e5SHanoh Haim                else:
151420216e5SHanoh Haim                    new_attr = old_attr
152420216e5SHanoh Haim            self.attr = new_attr
153420216e5SHanoh Haim        else:
154420216e5SHanoh Haim            self.mod = old_mod
155420216e5SHanoh Haim            if old_attr is None:
156420216e5SHanoh Haim                old_attr = name
157420216e5SHanoh Haim            self.attr = old_attr
158420216e5SHanoh Haim
159420216e5SHanoh Haim    def _resolve(self):
160420216e5SHanoh Haim        module = _import_module(self.mod)
161420216e5SHanoh Haim        return getattr(module, self.attr)
162420216e5SHanoh Haim
163420216e5SHanoh Haim
164420216e5SHanoh Haimclass _SixMetaPathImporter(object):
165420216e5SHanoh Haim
166420216e5SHanoh Haim    """
167420216e5SHanoh Haim    A meta path importer to import six.moves and its submodules.
168420216e5SHanoh Haim
169420216e5SHanoh Haim    This class implements a PEP302 finder and loader. It should be compatible
170420216e5SHanoh Haim    with Python 2.5 and all existing versions of Python3
171420216e5SHanoh Haim    """
172420216e5SHanoh Haim
173420216e5SHanoh Haim    def __init__(self, six_module_name):
174420216e5SHanoh Haim        self.name = six_module_name
175420216e5SHanoh Haim        self.known_modules = {}
176420216e5SHanoh Haim
177420216e5SHanoh Haim    def _add_module(self, mod, *fullnames):
178420216e5SHanoh Haim        for fullname in fullnames:
179420216e5SHanoh Haim            self.known_modules[self.name + "." + fullname] = mod
180420216e5SHanoh Haim
181420216e5SHanoh Haim    def _get_module(self, fullname):
182420216e5SHanoh Haim        return self.known_modules[self.name + "." + fullname]
183420216e5SHanoh Haim
184420216e5SHanoh Haim    def find_module(self, fullname, path=None):
185420216e5SHanoh Haim        if fullname in self.known_modules:
186420216e5SHanoh Haim            return self
187420216e5SHanoh Haim        return None
188420216e5SHanoh Haim
189420216e5SHanoh Haim    def __get_module(self, fullname):
190420216e5SHanoh Haim        try:
191420216e5SHanoh Haim            return self.known_modules[fullname]
192420216e5SHanoh Haim        except KeyError:
193420216e5SHanoh Haim            raise ImportError("This loader does not know module " + fullname)
194420216e5SHanoh Haim
195420216e5SHanoh Haim    def load_module(self, fullname):
196420216e5SHanoh Haim        try:
197420216e5SHanoh Haim            # in case of a reload
198420216e5SHanoh Haim            return sys.modules[fullname]
199420216e5SHanoh Haim        except KeyError:
200420216e5SHanoh Haim            pass
201420216e5SHanoh Haim        mod = self.__get_module(fullname)
202420216e5SHanoh Haim        if isinstance(mod, MovedModule):
203420216e5SHanoh Haim            mod = mod._resolve()
204420216e5SHanoh Haim        else:
205420216e5SHanoh Haim            mod.__loader__ = self
206420216e5SHanoh Haim        sys.modules[fullname] = mod
207420216e5SHanoh Haim        return mod
208420216e5SHanoh Haim
209420216e5SHanoh Haim    def is_package(self, fullname):
210420216e5SHanoh Haim        """
211420216e5SHanoh Haim        Return true, if the named module is a package.
212420216e5SHanoh Haim
213420216e5SHanoh Haim        We need this method to get correct spec objects with
214420216e5SHanoh Haim        Python 3.4 (see PEP451)
215420216e5SHanoh Haim        """
216420216e5SHanoh Haim        return hasattr(self.__get_module(fullname), "__path__")
217420216e5SHanoh Haim
218420216e5SHanoh Haim    def get_code(self, fullname):
219420216e5SHanoh Haim        """Return None
220420216e5SHanoh Haim
221420216e5SHanoh Haim        Required, if is_package is implemented"""
222420216e5SHanoh Haim        self.__get_module(fullname)  # eventually raises ImportError
223420216e5SHanoh Haim        return None
224420216e5SHanoh Haim    get_source = get_code  # same as get_code
225420216e5SHanoh Haim
226420216e5SHanoh Haim_importer = _SixMetaPathImporter(__name__)
227420216e5SHanoh Haim
228420216e5SHanoh Haim
229420216e5SHanoh Haimclass _MovedItems(_LazyModule):
230420216e5SHanoh Haim
231420216e5SHanoh Haim    """Lazy loading of moved objects"""
232420216e5SHanoh Haim    __path__ = []  # mark as package
233420216e5SHanoh Haim
234420216e5SHanoh Haim
235420216e5SHanoh Haim_moved_attributes = [
236420216e5SHanoh Haim    MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
237420216e5SHanoh Haim    MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
238420216e5SHanoh Haim    MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
239420216e5SHanoh Haim    MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
240420216e5SHanoh Haim    MovedAttribute("intern", "__builtin__", "sys"),
241420216e5SHanoh Haim    MovedAttribute("map", "itertools", "builtins", "imap", "map"),
242420216e5SHanoh Haim    MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
243420216e5SHanoh Haim    MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
244420216e5SHanoh Haim    MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
245420216e5SHanoh Haim    MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),
246420216e5SHanoh Haim    MovedAttribute("reduce", "__builtin__", "functools"),
247420216e5SHanoh Haim    MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
248420216e5SHanoh Haim    MovedAttribute("StringIO", "StringIO", "io"),
249420216e5SHanoh Haim    MovedAttribute("UserDict", "UserDict", "collections"),
250420216e5SHanoh Haim    MovedAttribute("UserList", "UserList", "collections"),
251420216e5SHanoh Haim    MovedAttribute("UserString", "UserString", "collections"),
252420216e5SHanoh Haim    MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
253420216e5SHanoh Haim    MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
254420216e5SHanoh Haim    MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
255420216e5SHanoh Haim    MovedModule("builtins", "__builtin__"),
256420216e5SHanoh Haim    MovedModule("configparser", "ConfigParser"),
257420216e5SHanoh Haim    MovedModule("copyreg", "copy_reg"),
258420216e5SHanoh Haim    MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
259420216e5SHanoh Haim    MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
260420216e5SHanoh Haim    MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
261420216e5SHanoh Haim    MovedModule("http_cookies", "Cookie", "http.cookies"),
262420216e5SHanoh Haim    MovedModule("html_entities", "htmlentitydefs", "html.entities"),
263420216e5SHanoh Haim    MovedModule("html_parser", "HTMLParser", "html.parser"),
264420216e5SHanoh Haim    MovedModule("http_client", "httplib", "http.client"),
265420216e5SHanoh Haim    MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
266420216e5SHanoh Haim    MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
267420216e5SHanoh Haim    MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
268420216e5SHanoh Haim    MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
269420216e5SHanoh Haim    MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
270420216e5SHanoh Haim    MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
271420216e5SHanoh Haim    MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
272420216e5SHanoh Haim    MovedModule("cPickle", "cPickle", "pickle"),
273420216e5SHanoh Haim    MovedModule("queue", "Queue"),
274420216e5SHanoh Haim    MovedModule("reprlib", "repr"),
275420216e5SHanoh Haim    MovedModule("socketserver", "SocketServer"),
276420216e5SHanoh Haim    MovedModule("_thread", "thread", "_thread"),
277420216e5SHanoh Haim    MovedModule("tkinter", "Tkinter"),
278420216e5SHanoh Haim    MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
279420216e5SHanoh Haim    MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
280420216e5SHanoh Haim    MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
281420216e5SHanoh Haim    MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
282420216e5SHanoh Haim    MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
283420216e5SHanoh Haim    MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
284420216e5SHanoh Haim    MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
285420216e5SHanoh Haim    MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
286420216e5SHanoh Haim    MovedModule("tkinter_colorchooser", "tkColorChooser",
287420216e5SHanoh Haim                "tkinter.colorchooser"),
288420216e5SHanoh Haim    MovedModule("tkinter_commondialog", "tkCommonDialog",
289420216e5SHanoh Haim                "tkinter.commondialog"),
290420216e5SHanoh Haim    MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
291420216e5SHanoh Haim    MovedModule("tkinter_font", "tkFont", "tkinter.font"),
292420216e5SHanoh Haim    MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
293420216e5SHanoh Haim    MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
294420216e5SHanoh Haim                "tkinter.simpledialog"),
295420216e5SHanoh Haim    MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
296420216e5SHanoh Haim    MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
297420216e5SHanoh Haim    MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
298420216e5SHanoh Haim    MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
299420216e5SHanoh Haim    MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
300420216e5SHanoh Haim    MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
301420216e5SHanoh Haim]
302420216e5SHanoh Haim# Add windows specific modules.
303420216e5SHanoh Haimif sys.platform == "win32":
304420216e5SHanoh Haim    _moved_attributes += [
305420216e5SHanoh Haim        MovedModule("winreg", "_winreg"),
306420216e5SHanoh Haim    ]
307420216e5SHanoh Haim
308420216e5SHanoh Haimfor attr in _moved_attributes:
309420216e5SHanoh Haim    setattr(_MovedItems, attr.name, attr)
310420216e5SHanoh Haim    if isinstance(attr, MovedModule):
311420216e5SHanoh Haim        _importer._add_module(attr, "moves." + attr.name)
312420216e5SHanoh Haimdel attr
313420216e5SHanoh Haim
314420216e5SHanoh Haim_MovedItems._moved_attributes = _moved_attributes
315420216e5SHanoh Haim
316420216e5SHanoh Haimmoves = _MovedItems(__name__ + ".moves")
317420216e5SHanoh Haim_importer._add_module(moves, "moves")
318420216e5SHanoh Haim
319420216e5SHanoh Haim
320420216e5SHanoh Haimclass Module_six_moves_urllib_parse(_LazyModule):
321420216e5SHanoh Haim
322420216e5SHanoh Haim    """Lazy loading of moved objects in six.moves.urllib_parse"""
323420216e5SHanoh Haim
324420216e5SHanoh Haim
325420216e5SHanoh Haim_urllib_parse_moved_attributes = [
326420216e5SHanoh Haim    MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
327420216e5SHanoh Haim    MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
328420216e5SHanoh Haim    MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
329420216e5SHanoh Haim    MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
330420216e5SHanoh Haim    MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
331420216e5SHanoh Haim    MovedAttribute("urljoin", "urlparse", "urllib.parse"),
332420216e5SHanoh Haim    MovedAttribute("urlparse", "urlparse", "urllib.parse"),
333420216e5SHanoh Haim    MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
334420216e5SHanoh Haim    MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
335420216e5SHanoh Haim    MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
336420216e5SHanoh Haim    MovedAttribute("quote", "urllib", "urllib.parse"),
337420216e5SHanoh Haim    MovedAttribute("quote_plus", "urllib", "urllib.parse"),
338420216e5SHanoh Haim    MovedAttribute("unquote", "urllib", "urllib.parse"),
339420216e5SHanoh Haim    MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
340420216e5SHanoh Haim    MovedAttribute("urlencode", "urllib", "urllib.parse"),
341420216e5SHanoh Haim    MovedAttribute("splitquery", "urllib", "urllib.parse"),
342420216e5SHanoh Haim    MovedAttribute("splittag", "urllib", "urllib.parse"),
343420216e5SHanoh Haim    MovedAttribute("splituser", "urllib", "urllib.parse"),
344420216e5SHanoh Haim    MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
345420216e5SHanoh Haim    MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
346420216e5SHanoh Haim    MovedAttribute("uses_params", "urlparse", "urllib.parse"),
347420216e5SHanoh Haim    MovedAttribute("uses_query", "urlparse", "urllib.parse"),
348420216e5SHanoh Haim    MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
349420216e5SHanoh Haim]
350420216e5SHanoh Haimfor attr in _urllib_parse_moved_attributes:
351420216e5SHanoh Haim    setattr(Module_six_moves_urllib_parse, attr.name, attr)
352420216e5SHanoh Haimdel attr
353420216e5SHanoh Haim
354420216e5SHanoh HaimModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
355420216e5SHanoh Haim
356420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
357420216e5SHanoh Haim                      "moves.urllib_parse", "moves.urllib.parse")
358420216e5SHanoh Haim
359420216e5SHanoh Haim
360420216e5SHanoh Haimclass Module_six_moves_urllib_error(_LazyModule):
361420216e5SHanoh Haim
362420216e5SHanoh Haim    """Lazy loading of moved objects in six.moves.urllib_error"""
363420216e5SHanoh Haim
364420216e5SHanoh Haim
365420216e5SHanoh Haim_urllib_error_moved_attributes = [
366420216e5SHanoh Haim    MovedAttribute("URLError", "urllib2", "urllib.error"),
367420216e5SHanoh Haim    MovedAttribute("HTTPError", "urllib2", "urllib.error"),
368420216e5SHanoh Haim    MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
369420216e5SHanoh Haim]
370420216e5SHanoh Haimfor attr in _urllib_error_moved_attributes:
371420216e5SHanoh Haim    setattr(Module_six_moves_urllib_error, attr.name, attr)
372420216e5SHanoh Haimdel attr
373420216e5SHanoh Haim
374420216e5SHanoh HaimModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
375420216e5SHanoh Haim
376420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
377420216e5SHanoh Haim                      "moves.urllib_error", "moves.urllib.error")
378420216e5SHanoh Haim
379420216e5SHanoh Haim
380420216e5SHanoh Haimclass Module_six_moves_urllib_request(_LazyModule):
381420216e5SHanoh Haim
382420216e5SHanoh Haim    """Lazy loading of moved objects in six.moves.urllib_request"""
383420216e5SHanoh Haim
384420216e5SHanoh Haim
385420216e5SHanoh Haim_urllib_request_moved_attributes = [
386420216e5SHanoh Haim    MovedAttribute("urlopen", "urllib2", "urllib.request"),
387420216e5SHanoh Haim    MovedAttribute("install_opener", "urllib2", "urllib.request"),
388420216e5SHanoh Haim    MovedAttribute("build_opener", "urllib2", "urllib.request"),
389420216e5SHanoh Haim    MovedAttribute("pathname2url", "urllib", "urllib.request"),
390420216e5SHanoh Haim    MovedAttribute("url2pathname", "urllib", "urllib.request"),
391420216e5SHanoh Haim    MovedAttribute("getproxies", "urllib", "urllib.request"),
392420216e5SHanoh Haim    MovedAttribute("Request", "urllib2", "urllib.request"),
393420216e5SHanoh Haim    MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
394420216e5SHanoh Haim    MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
395420216e5SHanoh Haim    MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
396420216e5SHanoh Haim    MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
397420216e5SHanoh Haim    MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
398420216e5SHanoh Haim    MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
399420216e5SHanoh Haim    MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
400420216e5SHanoh Haim    MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
401420216e5SHanoh Haim    MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
402420216e5SHanoh Haim    MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
403420216e5SHanoh Haim    MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
404420216e5SHanoh Haim    MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
405420216e5SHanoh Haim    MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
406420216e5SHanoh Haim    MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
407420216e5SHanoh Haim    MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
408420216e5SHanoh Haim    MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
409420216e5SHanoh Haim    MovedAttribute("FileHandler", "urllib2", "urllib.request"),
410420216e5SHanoh Haim    MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
411420216e5SHanoh Haim    MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
412420216e5SHanoh Haim    MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
413420216e5SHanoh Haim    MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
414420216e5SHanoh Haim    MovedAttribute("urlretrieve", "urllib", "urllib.request"),
415420216e5SHanoh Haim    MovedAttribute("urlcleanup", "urllib", "urllib.request"),
416420216e5SHanoh Haim    MovedAttribute("URLopener", "urllib", "urllib.request"),
417420216e5SHanoh Haim    MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
418420216e5SHanoh Haim    MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
419420216e5SHanoh Haim]
420420216e5SHanoh Haimfor attr in _urllib_request_moved_attributes:
421420216e5SHanoh Haim    setattr(Module_six_moves_urllib_request, attr.name, attr)
422420216e5SHanoh Haimdel attr
423420216e5SHanoh Haim
424420216e5SHanoh HaimModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
425420216e5SHanoh Haim
426420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
427420216e5SHanoh Haim                      "moves.urllib_request", "moves.urllib.request")
428420216e5SHanoh Haim
429420216e5SHanoh Haim
430420216e5SHanoh Haimclass Module_six_moves_urllib_response(_LazyModule):
431420216e5SHanoh Haim
432420216e5SHanoh Haim    """Lazy loading of moved objects in six.moves.urllib_response"""
433420216e5SHanoh Haim
434420216e5SHanoh Haim
435420216e5SHanoh Haim_urllib_response_moved_attributes = [
436420216e5SHanoh Haim    MovedAttribute("addbase", "urllib", "urllib.response"),
437420216e5SHanoh Haim    MovedAttribute("addclosehook", "urllib", "urllib.response"),
438420216e5SHanoh Haim    MovedAttribute("addinfo", "urllib", "urllib.response"),
439420216e5SHanoh Haim    MovedAttribute("addinfourl", "urllib", "urllib.response"),
440420216e5SHanoh Haim]
441420216e5SHanoh Haimfor attr in _urllib_response_moved_attributes:
442420216e5SHanoh Haim    setattr(Module_six_moves_urllib_response, attr.name, attr)
443420216e5SHanoh Haimdel attr
444420216e5SHanoh Haim
445420216e5SHanoh HaimModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
446420216e5SHanoh Haim
447420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
448420216e5SHanoh Haim                      "moves.urllib_response", "moves.urllib.response")
449420216e5SHanoh Haim
450420216e5SHanoh Haim
451420216e5SHanoh Haimclass Module_six_moves_urllib_robotparser(_LazyModule):
452420216e5SHanoh Haim
453420216e5SHanoh Haim    """Lazy loading of moved objects in six.moves.urllib_robotparser"""
454420216e5SHanoh Haim
455420216e5SHanoh Haim
456420216e5SHanoh Haim_urllib_robotparser_moved_attributes = [
457420216e5SHanoh Haim    MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
458420216e5SHanoh Haim]
459420216e5SHanoh Haimfor attr in _urllib_robotparser_moved_attributes:
460420216e5SHanoh Haim    setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
461420216e5SHanoh Haimdel attr
462420216e5SHanoh Haim
463420216e5SHanoh HaimModule_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
464420216e5SHanoh Haim
465420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
466420216e5SHanoh Haim                      "moves.urllib_robotparser", "moves.urllib.robotparser")
467420216e5SHanoh Haim
468420216e5SHanoh Haim
469420216e5SHanoh Haimclass Module_six_moves_urllib(types.ModuleType):
470420216e5SHanoh Haim
471420216e5SHanoh Haim    """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
472420216e5SHanoh Haim    __path__ = []  # mark as package
473420216e5SHanoh Haim    parse = _importer._get_module("moves.urllib_parse")
474420216e5SHanoh Haim    error = _importer._get_module("moves.urllib_error")
475420216e5SHanoh Haim    request = _importer._get_module("moves.urllib_request")
476420216e5SHanoh Haim    response = _importer._get_module("moves.urllib_response")
477420216e5SHanoh Haim    robotparser = _importer._get_module("moves.urllib_robotparser")
478420216e5SHanoh Haim
479420216e5SHanoh Haim    def __dir__(self):
480420216e5SHanoh Haim        return ['parse', 'error', 'request', 'response', 'robotparser']
481420216e5SHanoh Haim
482420216e5SHanoh Haim_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
483420216e5SHanoh Haim                      "moves.urllib")
484420216e5SHanoh Haim
485420216e5SHanoh Haim
486420216e5SHanoh Haimdef add_move(move):
487420216e5SHanoh Haim    """Add an item to six.moves."""
488420216e5SHanoh Haim    setattr(_MovedItems, move.name, move)
489420216e5SHanoh Haim
490420216e5SHanoh Haim
491420216e5SHanoh Haimdef remove_move(name):
492420216e5SHanoh Haim    """Remove item from six.moves."""
493420216e5SHanoh Haim    try:
494420216e5SHanoh Haim        delattr(_MovedItems, name)
495420216e5SHanoh Haim    except AttributeError:
496420216e5SHanoh Haim        try:
497420216e5SHanoh Haim            del moves.__dict__[name]
498420216e5SHanoh Haim        except KeyError:
499420216e5SHanoh Haim            raise AttributeError("no such move, %r" % (name,))
500420216e5SHanoh Haim
501420216e5SHanoh Haim
502420216e5SHanoh Haimif PY3:
503420216e5SHanoh Haim    _meth_func = "__func__"
504420216e5SHanoh Haim    _meth_self = "__self__"
505420216e5SHanoh Haim
506420216e5SHanoh Haim    _func_closure = "__closure__"
507420216e5SHanoh Haim    _func_code = "__code__"
508420216e5SHanoh Haim    _func_defaults = "__defaults__"
509420216e5SHanoh Haim    _func_globals = "__globals__"
510420216e5SHanoh Haimelse:
511420216e5SHanoh Haim    _meth_func = "im_func"
512420216e5SHanoh Haim    _meth_self = "im_self"
513420216e5SHanoh Haim
514420216e5SHanoh Haim    _func_closure = "func_closure"
515420216e5SHanoh Haim    _func_code = "func_code"
516420216e5SHanoh Haim    _func_defaults = "func_defaults"
517420216e5SHanoh Haim    _func_globals = "func_globals"
518420216e5SHanoh Haim
519420216e5SHanoh Haim
520420216e5SHanoh Haimtry:
521420216e5SHanoh Haim    advance_iterator = next
522420216e5SHanoh Haimexcept NameError:
523420216e5SHanoh Haim    def advance_iterator(it):
524420216e5SHanoh Haim        return it.next()
525420216e5SHanoh Haimnext = advance_iterator
526420216e5SHanoh Haim
527420216e5SHanoh Haim
528420216e5SHanoh Haimtry:
529420216e5SHanoh Haim    callable = callable
530420216e5SHanoh Haimexcept NameError:
531420216e5SHanoh Haim    def callable(obj):
532420216e5SHanoh Haim        return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
533420216e5SHanoh Haim
534420216e5SHanoh Haim
535420216e5SHanoh Haimif PY3:
536420216e5SHanoh Haim    def get_unbound_function(unbound):
537420216e5SHanoh Haim        return unbound
538420216e5SHanoh Haim
539420216e5SHanoh Haim    create_bound_method = types.MethodType
540420216e5SHanoh Haim
541420216e5SHanoh Haim    def create_unbound_method(func, cls):
542420216e5SHanoh Haim        return func
543420216e5SHanoh Haim
544420216e5SHanoh Haim    Iterator = object
545420216e5SHanoh Haimelse:
546420216e5SHanoh Haim    def get_unbound_function(unbound):
547420216e5SHanoh Haim        return unbound.im_func
548420216e5SHanoh Haim
549420216e5SHanoh Haim    def create_bound_method(func, obj):
550420216e5SHanoh Haim        return types.MethodType(func, obj, obj.__class__)
551420216e5SHanoh Haim
552420216e5SHanoh Haim    def create_unbound_method(func, cls):
553420216e5SHanoh Haim        return types.MethodType(func, None, cls)
554420216e5SHanoh Haim
555420216e5SHanoh Haim    class Iterator(object):
556420216e5SHanoh Haim
557420216e5SHanoh Haim        def next(self):
558420216e5SHanoh Haim            return type(self).__next__(self)
559420216e5SHanoh Haim
560420216e5SHanoh Haim    callable = callable
561420216e5SHanoh Haim_add_doc(get_unbound_function,
562420216e5SHanoh Haim         """Get the function out of a possibly unbound function""")
563420216e5SHanoh Haim
564420216e5SHanoh Haim
565420216e5SHanoh Haimget_method_function = operator.attrgetter(_meth_func)
566420216e5SHanoh Haimget_method_self = operator.attrgetter(_meth_self)
567420216e5SHanoh Haimget_function_closure = operator.attrgetter(_func_closure)
568420216e5SHanoh Haimget_function_code = operator.attrgetter(_func_code)
569420216e5SHanoh Haimget_function_defaults = operator.attrgetter(_func_defaults)
570420216e5SHanoh Haimget_function_globals = operator.attrgetter(_func_globals)
571420216e5SHanoh Haim
572420216e5SHanoh Haim
573420216e5SHanoh Haimif PY3:
574420216e5SHanoh Haim    def iterkeys(d, **kw):
575420216e5SHanoh Haim        return iter(d.keys(**kw))
576420216e5SHanoh Haim
577420216e5SHanoh Haim    def itervalues(d, **kw):
578420216e5SHanoh Haim        return iter(d.values(**kw))
579420216e5SHanoh Haim
580420216e5SHanoh Haim    def iteritems(d, **kw):
581420216e5SHanoh Haim        return iter(d.items(**kw))
582420216e5SHanoh Haim
583420216e5SHanoh Haim    def iterlists(d, **kw):
584420216e5SHanoh Haim        return iter(d.lists(**kw))
585420216e5SHanoh Haim
586420216e5SHanoh Haim    viewkeys = operator.methodcaller("keys")
587420216e5SHanoh Haim
588420216e5SHanoh Haim    viewvalues = operator.methodcaller("values")
589420216e5SHanoh Haim
590420216e5SHanoh Haim    viewitems = operator.methodcaller("items")
591420216e5SHanoh Haimelse:
592420216e5SHanoh Haim    def iterkeys(d, **kw):
593420216e5SHanoh Haim        return d.iterkeys(**kw)
594420216e5SHanoh Haim
595420216e5SHanoh Haim    def itervalues(d, **kw):
596420216e5SHanoh Haim        return d.itervalues(**kw)
597420216e5SHanoh Haim
598420216e5SHanoh Haim    def iteritems(d, **kw):
599420216e5SHanoh Haim        return d.iteritems(**kw)
600420216e5SHanoh Haim
601420216e5SHanoh Haim    def iterlists(d, **kw):
602420216e5SHanoh Haim        return d.iterlists(**kw)
603420216e5SHanoh Haim
604420216e5SHanoh Haim    viewkeys = operator.methodcaller("viewkeys")
605420216e5SHanoh Haim
606420216e5SHanoh Haim    viewvalues = operator.methodcaller("viewvalues")
607420216e5SHanoh Haim
608420216e5SHanoh Haim    viewitems = operator.methodcaller("viewitems")
609420216e5SHanoh Haim
610420216e5SHanoh Haim_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
611420216e5SHanoh Haim_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
612420216e5SHanoh Haim_add_doc(iteritems,
613420216e5SHanoh Haim         "Return an iterator over the (key, value) pairs of a dictionary.")
614420216e5SHanoh Haim_add_doc(iterlists,
615420216e5SHanoh Haim         "Return an iterator over the (key, [values]) pairs of a dictionary.")
616420216e5SHanoh Haim
617420216e5SHanoh Haim
618420216e5SHanoh Haimif PY3:
619420216e5SHanoh Haim    def b(s):
620420216e5SHanoh Haim        return s.encode("latin-1")
621420216e5SHanoh Haim
622420216e5SHanoh Haim    def u(s):
623420216e5SHanoh Haim        return s
624420216e5SHanoh Haim    unichr = chr
625420216e5SHanoh Haim    import struct
626420216e5SHanoh Haim    int2byte = struct.Struct(">B").pack
627420216e5SHanoh Haim    del struct
628420216e5SHanoh Haim    byte2int = operator.itemgetter(0)
629420216e5SHanoh Haim    indexbytes = operator.getitem
630420216e5SHanoh Haim    iterbytes = iter
631420216e5SHanoh Haim    import io
632420216e5SHanoh Haim    StringIO = io.StringIO
633420216e5SHanoh Haim    BytesIO = io.BytesIO
634420216e5SHanoh Haim    _assertCountEqual = "assertCountEqual"
635420216e5SHanoh Haim    if sys.version_info[1] <= 1:
636420216e5SHanoh Haim        _assertRaisesRegex = "assertRaisesRegexp"
637420216e5SHanoh Haim        _assertRegex = "assertRegexpMatches"
638420216e5SHanoh Haim    else:
639420216e5SHanoh Haim        _assertRaisesRegex = "assertRaisesRegex"
640420216e5SHanoh Haim        _assertRegex = "assertRegex"
641420216e5SHanoh Haimelse:
642420216e5SHanoh Haim    def b(s):
643420216e5SHanoh Haim        return s
644420216e5SHanoh Haim    # Workaround for standalone backslash
645420216e5SHanoh Haim
646420216e5SHanoh Haim    def u(s):
647420216e5SHanoh Haim        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
648420216e5SHanoh Haim    unichr = unichr
649420216e5SHanoh Haim    int2byte = chr
650420216e5SHanoh Haim
651420216e5SHanoh Haim    def byte2int(bs):
652420216e5SHanoh Haim        return ord(bs[0])
653420216e5SHanoh Haim
654420216e5SHanoh Haim    def indexbytes(buf, i):
655420216e5SHanoh Haim        return ord(buf[i])
656420216e5SHanoh Haim    iterbytes = functools.partial(itertools.imap, ord)
657420216e5SHanoh Haim    import StringIO
658420216e5SHanoh Haim    StringIO = BytesIO = StringIO.StringIO
659420216e5SHanoh Haim    _assertCountEqual = "assertItemsEqual"
660420216e5SHanoh Haim    _assertRaisesRegex = "assertRaisesRegexp"
661420216e5SHanoh Haim    _assertRegex = "assertRegexpMatches"
662420216e5SHanoh Haim_add_doc(b, """Byte literal""")
663420216e5SHanoh Haim_add_doc(u, """Text literal""")
664420216e5SHanoh Haim
665420216e5SHanoh Haim
666420216e5SHanoh Haimdef assertCountEqual(self, *args, **kwargs):
667420216e5SHanoh Haim    return getattr(self, _assertCountEqual)(*args, **kwargs)
668420216e5SHanoh Haim
669420216e5SHanoh Haim
670420216e5SHanoh Haimdef assertRaisesRegex(self, *args, **kwargs):
671420216e5SHanoh Haim    return getattr(self, _assertRaisesRegex)(*args, **kwargs)
672420216e5SHanoh Haim
673420216e5SHanoh Haim
674420216e5SHanoh Haimdef assertRegex(self, *args, **kwargs):
675420216e5SHanoh Haim    return getattr(self, _assertRegex)(*args, **kwargs)
676420216e5SHanoh Haim
677420216e5SHanoh Haim
678420216e5SHanoh Haimif PY3:
679420216e5SHanoh Haim    exec_ = getattr(moves.builtins, "exec")
680420216e5SHanoh Haim
681420216e5SHanoh Haim    def reraise(tp, value, tb=None):
682420216e5SHanoh Haim        if value is None:
683420216e5SHanoh Haim            value = tp()
684420216e5SHanoh Haim        if value.__traceback__ is not tb:
685420216e5SHanoh Haim            raise value.with_traceback(tb)
686420216e5SHanoh Haim        raise value
687420216e5SHanoh Haim
688420216e5SHanoh Haimelse:
689420216e5SHanoh Haim    def exec_(_code_, _globs_=None, _locs_=None):
690420216e5SHanoh Haim        """Execute code in a namespace."""
691420216e5SHanoh Haim        if _globs_ is None:
692420216e5SHanoh Haim            frame = sys._getframe(1)
693420216e5SHanoh Haim            _globs_ = frame.f_globals
694420216e5SHanoh Haim            if _locs_ is None:
695420216e5SHanoh Haim                _locs_ = frame.f_locals
696420216e5SHanoh Haim            del frame
697420216e5SHanoh Haim        elif _locs_ is None:
698420216e5SHanoh Haim            _locs_ = _globs_
699420216e5SHanoh Haim        exec("""exec _code_ in _globs_, _locs_""")
700420216e5SHanoh Haim
701420216e5SHanoh Haim    exec_("""def reraise(tp, value, tb=None):
702420216e5SHanoh Haim    raise tp, value, tb
703420216e5SHanoh Haim""")
704420216e5SHanoh Haim
705420216e5SHanoh Haim
706420216e5SHanoh Haimif sys.version_info[:2] == (3, 2):
707420216e5SHanoh Haim    exec_("""def raise_from(value, from_value):
708420216e5SHanoh Haim    if from_value is None:
709420216e5SHanoh Haim        raise value
710420216e5SHanoh Haim    raise value from from_value
711420216e5SHanoh Haim""")
712420216e5SHanoh Haimelif sys.version_info[:2] > (3, 2):
713420216e5SHanoh Haim    exec_("""def raise_from(value, from_value):
714420216e5SHanoh Haim    raise value from from_value
715420216e5SHanoh Haim""")
716420216e5SHanoh Haimelse:
717420216e5SHanoh Haim    def raise_from(value, from_value):
718420216e5SHanoh Haim        raise value
719420216e5SHanoh Haim
720420216e5SHanoh Haim
721420216e5SHanoh Haimprint_ = getattr(moves.builtins, "print", None)
722420216e5SHanoh Haimif print_ is None:
723420216e5SHanoh Haim    def print_(*args, **kwargs):
724420216e5SHanoh Haim        """The new-style print function for Python 2.4 and 2.5."""
725420216e5SHanoh Haim        fp = kwargs.pop("file", sys.stdout)
726420216e5SHanoh Haim        if fp is None:
727420216e5SHanoh Haim            return
728420216e5SHanoh Haim
729420216e5SHanoh Haim        def write(data):
730420216e5SHanoh Haim            if not isinstance(data, basestring):
731420216e5SHanoh Haim                data = str(data)
732420216e5SHanoh Haim            # If the file has an encoding, encode unicode with it.
733420216e5SHanoh Haim            if (isinstance(fp, file) and
734420216e5SHanoh Haim                    isinstance(data, unicode) and
735420216e5SHanoh Haim                    fp.encoding is not None):
736420216e5SHanoh Haim                errors = getattr(fp, "errors", None)
737420216e5SHanoh Haim                if errors is None:
738420216e5SHanoh Haim                    errors = "strict"
739420216e5SHanoh Haim                data = data.encode(fp.encoding, errors)
740420216e5SHanoh Haim            fp.write(data)
741420216e5SHanoh Haim        want_unicode = False
742420216e5SHanoh Haim        sep = kwargs.pop("sep", None)
743420216e5SHanoh Haim        if sep is not None:
744420216e5SHanoh Haim            if isinstance(sep, unicode):
745420216e5SHanoh Haim                want_unicode = True
746420216e5SHanoh Haim            elif not isinstance(sep, str):
747420216e5SHanoh Haim                raise TypeError("sep must be None or a string")
748420216e5SHanoh Haim        end = kwargs.pop("end", None)
749420216e5SHanoh Haim        if end is not None:
750420216e5SHanoh Haim            if isinstance(end, unicode):
751420216e5SHanoh Haim                want_unicode = True
752420216e5SHanoh Haim            elif not isinstance(end, str):
753420216e5SHanoh Haim                raise TypeError("end must be None or a string")
754420216e5SHanoh Haim        if kwargs:
755420216e5SHanoh Haim            raise TypeError("invalid keyword arguments to print()")
756420216e5SHanoh Haim        if not want_unicode:
757420216e5SHanoh Haim            for arg in args:
758420216e5SHanoh Haim                if isinstance(arg, unicode):
759420216e5SHanoh Haim                    want_unicode = True
760420216e5SHanoh Haim                    break
761420216e5SHanoh Haim        if want_unicode:
762420216e5SHanoh Haim            newline = unicode("\n")
763420216e5SHanoh Haim            space = unicode(" ")
764420216e5SHanoh Haim        else:
765420216e5SHanoh Haim            newline = "\n"
766420216e5SHanoh Haim            space = " "
767420216e5SHanoh Haim        if sep is None:
768420216e5SHanoh Haim            sep = space
769420216e5SHanoh Haim        if end is None:
770420216e5SHanoh Haim            end = newline
771420216e5SHanoh Haim        for i, arg in enumerate(args):
772420216e5SHanoh Haim            if i:
773420216e5SHanoh Haim                write(sep)
774420216e5SHanoh Haim            write(arg)
775420216e5SHanoh Haim        write(end)
776420216e5SHanoh Haimif sys.version_info[:2] < (3, 3):
777420216e5SHanoh Haim    _print = print_
778420216e5SHanoh Haim
779420216e5SHanoh Haim    def print_(*args, **kwargs):
780420216e5SHanoh Haim        fp = kwargs.get("file", sys.stdout)
781420216e5SHanoh Haim        flush = kwargs.pop("flush", False)
782420216e5SHanoh Haim        _print(*args, **kwargs)
783420216e5SHanoh Haim        if flush and fp is not None:
784420216e5SHanoh Haim            fp.flush()
785420216e5SHanoh Haim
786420216e5SHanoh Haim_add_doc(reraise, """Reraise an exception.""")
787420216e5SHanoh Haim
788420216e5SHanoh Haimif sys.version_info[0:2] < (3, 4):
789420216e5SHanoh Haim    def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
790420216e5SHanoh Haim              updated=functools.WRAPPER_UPDATES):
791420216e5SHanoh Haim        def wrapper(f):
792420216e5SHanoh Haim            f = functools.wraps(wrapped, assigned, updated)(f)
793420216e5SHanoh Haim            f.__wrapped__ = wrapped
794420216e5SHanoh Haim            return f
795420216e5SHanoh Haim        return wrapper
796420216e5SHanoh Haimelse:
797420216e5SHanoh Haim    wraps = functools.wraps
798420216e5SHanoh Haim
799420216e5SHanoh Haim
800420216e5SHanoh Haimdef with_metaclass(meta, *bases):
801420216e5SHanoh Haim    """Create a base class with a metaclass."""
802420216e5SHanoh Haim    # This requires a bit of explanation: the basic idea is to make a dummy
803420216e5SHanoh Haim    # metaclass for one level of class instantiation that replaces itself with
804420216e5SHanoh Haim    # the actual metaclass.
805420216e5SHanoh Haim    class metaclass(meta):
806420216e5SHanoh Haim
807420216e5SHanoh Haim        def __new__(cls, name, this_bases, d):
808420216e5SHanoh Haim            return meta(name, bases, d)
809420216e5SHanoh Haim    return type.__new__(metaclass, 'temporary_class', (), {})
810420216e5SHanoh Haim
811420216e5SHanoh Haim
812420216e5SHanoh Haimdef add_metaclass(metaclass):
813420216e5SHanoh Haim    """Class decorator for creating a class with a metaclass."""
814420216e5SHanoh Haim    def wrapper(cls):
815420216e5SHanoh Haim        orig_vars = cls.__dict__.copy()
816420216e5SHanoh Haim        slots = orig_vars.get('__slots__')
817420216e5SHanoh Haim        if slots is not None:
818420216e5SHanoh Haim            if isinstance(slots, str):
819420216e5SHanoh Haim                slots = [slots]
820420216e5SHanoh Haim            for slots_var in slots:
821420216e5SHanoh Haim                orig_vars.pop(slots_var)
822420216e5SHanoh Haim        orig_vars.pop('__dict__', None)
823420216e5SHanoh Haim        orig_vars.pop('__weakref__', None)
824420216e5SHanoh Haim        return metaclass(cls.__name__, cls.__bases__, orig_vars)
825420216e5SHanoh Haim    return wrapper
826420216e5SHanoh Haim
827420216e5SHanoh Haim
828420216e5SHanoh Haimdef python_2_unicode_compatible(klass):
829420216e5SHanoh Haim    """
830420216e5SHanoh Haim    A decorator that defines __unicode__ and __str__ methods under Python 2.
831420216e5SHanoh Haim    Under Python 3 it does nothing.
832420216e5SHanoh Haim
833420216e5SHanoh Haim    To support Python 2 and 3 with a single code base, define a __str__ method
834420216e5SHanoh Haim    returning text and apply this decorator to the class.
835420216e5SHanoh Haim    """
836420216e5SHanoh Haim    if PY2:
837420216e5SHanoh Haim        if '__str__' not in klass.__dict__:
838420216e5SHanoh Haim            raise ValueError("@python_2_unicode_compatible cannot be applied "
839420216e5SHanoh Haim                             "to %s because it doesn't define __str__()." %
840420216e5SHanoh Haim                             klass.__name__)
841420216e5SHanoh Haim        klass.__unicode__ = klass.__str__
842420216e5SHanoh Haim        klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
843420216e5SHanoh Haim    return klass
844420216e5SHanoh Haim
845420216e5SHanoh Haim
846420216e5SHanoh Haim# Complete the moves implementation.
847420216e5SHanoh Haim# This code is at the end of this module to speed up module loading.
848420216e5SHanoh Haim# Turn this module into a package.
849420216e5SHanoh Haim__path__ = []  # required for PEP 302 and PEP 451
850420216e5SHanoh Haim__package__ = __name__  # see PEP 366 @ReservedAssignment
851420216e5SHanoh Haimif globals().get("__spec__") is not None:
852420216e5SHanoh Haim    __spec__.submodule_search_locations = []  # PEP 451 @UndefinedVariable
853420216e5SHanoh Haim# Remove other six meta path importers, since they cause problems. This can
854420216e5SHanoh Haim# happen if six is removed from sys.modules and then reloaded. (Setuptools does
855420216e5SHanoh Haim# this for some reason.)
856420216e5SHanoh Haimif sys.meta_path:
857420216e5SHanoh Haim    for i, importer in enumerate(sys.meta_path):
858420216e5SHanoh Haim        # Here's some real nastiness: Another "instance" of the six module might
859420216e5SHanoh Haim        # be floating around. Therefore, we can't use isinstance() to check for
860420216e5SHanoh Haim        # the six meta path importer, since the other six instance will have
861420216e5SHanoh Haim        # inserted an importer with different class.
862420216e5SHanoh Haim        if (type(importer).__name__ == "_SixMetaPathImporter" and
863420216e5SHanoh Haim                importer.name == __name__):
864420216e5SHanoh Haim            del sys.meta_path[i]
865420216e5SHanoh Haim            break
866420216e5SHanoh Haim    del i, importer
867420216e5SHanoh Haim# Finally, add the importer to the meta path import hook.
868420216e5SHanoh Haimsys.meta_path.append(_importer)
869