diff --git a/build.py b/build.py index ca27710e..420df995 100755 --- a/build.py +++ b/build.py @@ -13,8 +13,6 @@ # License: wxWindows License #---------------------------------------------------------------------- -from __future__ import absolute_import - import sys import glob import hashlib diff --git a/buildtools/backports/six.py b/buildtools/backports/six.py deleted file mode 100644 index 89b2188f..00000000 --- a/buildtools/backports/six.py +++ /dev/null @@ -1,952 +0,0 @@ -# Copyright (c) 2010-2018 Benjamin Peterson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -"""Utilities for writing code that runs on Python 2 and 3""" - -from __future__ import absolute_import - -import functools -import itertools -import operator -import sys -import types - -__author__ = "Benjamin Peterson " -__version__ = "1.12.0" - - -# Useful for very coarse version differentiation. -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 -PY34 = sys.version_info[0:2] >= (3, 4) - -if PY3: - string_types = str, - integer_types = int, - class_types = type, - text_type = str - binary_type = bytes - - MAXSIZE = sys.maxsize -else: - string_types = basestring, - integer_types = (int, long) - class_types = (type, types.ClassType) - text_type = unicode - binary_type = str - - if sys.platform.startswith("java"): - # Jython always uses 32 bits. - MAXSIZE = int((1 << 31) - 1) - else: - # It's possible to have sizeof(long) != sizeof(Py_ssize_t). - class X(object): - - def __len__(self): - return 1 << 31 - try: - len(X()) - except OverflowError: - # 32-bit - MAXSIZE = int((1 << 31) - 1) - else: - # 64-bit - MAXSIZE = int((1 << 63) - 1) - del X - - -def _add_doc(func, doc): - """Add documentation to a function.""" - func.__doc__ = doc - - -def _import_module(name): - """Import module, returning the module after the last dot.""" - __import__(name) - return sys.modules[name] - - -class _LazyDescr(object): - - def __init__(self, name): - self.name = name - - def __get__(self, obj, tp): - result = self._resolve() - setattr(obj, self.name, result) # Invokes __set__. - try: - # This is a bit ugly, but it avoids running this again by - # removing this descriptor. - delattr(obj.__class__, self.name) - except AttributeError: - pass - return result - - -class MovedModule(_LazyDescr): - - def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) - if PY3: - if new is None: - new = name - self.mod = new - else: - self.mod = old - - def _resolve(self): - return _import_module(self.mod) - - def __getattr__(self, attr): - _module = self._resolve() - value = getattr(_module, attr) - setattr(self, attr, value) - return value - - -class _LazyModule(types.ModuleType): - - def __init__(self, name): - super(_LazyModule, self).__init__(name) - self.__doc__ = self.__class__.__doc__ - - def __dir__(self): - attrs = ["__doc__", "__name__"] - attrs += [attr.name for attr in self._moved_attributes] - return attrs - - # Subclasses should override this - _moved_attributes = [] - - -class MovedAttribute(_LazyDescr): - - def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) - if PY3: - if new_mod is None: - new_mod = name - self.mod = new_mod - if new_attr is None: - if old_attr is None: - new_attr = name - else: - new_attr = old_attr - self.attr = new_attr - else: - self.mod = old_mod - if old_attr is None: - old_attr = name - self.attr = old_attr - - def _resolve(self): - module = _import_module(self.mod) - return getattr(module, self.attr) - - -class _SixMetaPathImporter(object): - - """ - A meta path importer to import six.moves and its submodules. - - This class implements a PEP302 finder and loader. It should be compatible - with Python 2.5 and all existing versions of Python3 - """ - - def __init__(self, six_module_name): - self.name = six_module_name - self.known_modules = {} - - def _add_module(self, mod, *fullnames): - for fullname in fullnames: - self.known_modules[self.name + "." + fullname] = mod - - def _get_module(self, fullname): - return self.known_modules[self.name + "." + fullname] - - def find_module(self, fullname, path=None): - if fullname in self.known_modules: - return self - return None - - def __get_module(self, fullname): - try: - return self.known_modules[fullname] - except KeyError: - raise ImportError("This loader does not know module " + fullname) - - def load_module(self, fullname): - try: - # in case of a reload - return sys.modules[fullname] - except KeyError: - pass - mod = self.__get_module(fullname) - if isinstance(mod, MovedModule): - mod = mod._resolve() - else: - mod.__loader__ = self - sys.modules[fullname] = mod - return mod - - def is_package(self, fullname): - """ - Return true, if the named module is a package. - - We need this method to get correct spec objects with - Python 3.4 (see PEP451) - """ - return hasattr(self.__get_module(fullname), "__path__") - - def get_code(self, fullname): - """Return None - - Required, if is_package is implemented""" - self.__get_module(fullname) # eventually raises ImportError - return None - get_source = get_code # same as get_code - -_importer = _SixMetaPathImporter(__name__) - - -class _MovedItems(_LazyModule): - - """Lazy loading of moved objects""" - __path__ = [] # mark as package - - -_moved_attributes = [ - MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), - MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), - MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), - MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), - MovedAttribute("intern", "__builtin__", "sys"), - MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), - MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), - MovedAttribute("getoutput", "commands", "subprocess"), - MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), - MovedAttribute("reduce", "__builtin__", "functools"), - MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), - MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserDict", "UserDict", "collections"), - MovedAttribute("UserList", "UserList", "collections"), - MovedAttribute("UserString", "UserString", "collections"), - MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - MovedModule("builtins", "__builtin__"), - MovedModule("configparser", "ConfigParser"), - MovedModule("copyreg", "copy_reg"), - MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), - MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), - MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), - MovedModule("http_cookies", "Cookie", "http.cookies"), - MovedModule("html_entities", "htmlentitydefs", "html.entities"), - MovedModule("html_parser", "HTMLParser", "html.parser"), - MovedModule("http_client", "httplib", "http.client"), - MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), - MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), - MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), - MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), - MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), - MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), - MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), - MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), - MovedModule("cPickle", "cPickle", "pickle"), - MovedModule("queue", "Queue"), - MovedModule("reprlib", "repr"), - MovedModule("socketserver", "SocketServer"), - MovedModule("_thread", "thread", "_thread"), - MovedModule("tkinter", "Tkinter"), - MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), - MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), - MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), - MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), - MovedModule("tkinter_tix", "Tix", "tkinter.tix"), - MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), - MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), - MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), - MovedModule("tkinter_colorchooser", "tkColorChooser", - "tkinter.colorchooser"), - MovedModule("tkinter_commondialog", "tkCommonDialog", - "tkinter.commondialog"), - MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), - MovedModule("tkinter_font", "tkFont", "tkinter.font"), - MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), - MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", - "tkinter.simpledialog"), - MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), - MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), - MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), - MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), - MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), -] -# Add windows specific modules. -if sys.platform == "win32": - _moved_attributes += [ - MovedModule("winreg", "_winreg"), - ] - -for attr in _moved_attributes: - setattr(_MovedItems, attr.name, attr) - if isinstance(attr, MovedModule): - _importer._add_module(attr, "moves." + attr.name) -del attr - -_MovedItems._moved_attributes = _moved_attributes - -moves = _MovedItems(__name__ + ".moves") -_importer._add_module(moves, "moves") - - -class Module_six_moves_urllib_parse(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_parse""" - - -_urllib_parse_moved_attributes = [ - MovedAttribute("ParseResult", "urlparse", "urllib.parse"), - MovedAttribute("SplitResult", "urlparse", "urllib.parse"), - MovedAttribute("parse_qs", "urlparse", "urllib.parse"), - MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), - MovedAttribute("urldefrag", "urlparse", "urllib.parse"), - MovedAttribute("urljoin", "urlparse", "urllib.parse"), - MovedAttribute("urlparse", "urlparse", "urllib.parse"), - MovedAttribute("urlsplit", "urlparse", "urllib.parse"), - MovedAttribute("urlunparse", "urlparse", "urllib.parse"), - MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), - MovedAttribute("quote", "urllib", "urllib.parse"), - MovedAttribute("quote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote", "urllib", "urllib.parse"), - MovedAttribute("unquote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), - MovedAttribute("urlencode", "urllib", "urllib.parse"), - MovedAttribute("splitquery", "urllib", "urllib.parse"), - MovedAttribute("splittag", "urllib", "urllib.parse"), - MovedAttribute("splituser", "urllib", "urllib.parse"), - MovedAttribute("splitvalue", "urllib", "urllib.parse"), - MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), - MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), - MovedAttribute("uses_params", "urlparse", "urllib.parse"), - MovedAttribute("uses_query", "urlparse", "urllib.parse"), - MovedAttribute("uses_relative", "urlparse", "urllib.parse"), -] -for attr in _urllib_parse_moved_attributes: - setattr(Module_six_moves_urllib_parse, attr.name, attr) -del attr - -Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes - -_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), - "moves.urllib_parse", "moves.urllib.parse") - - -class Module_six_moves_urllib_error(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_error""" - - -_urllib_error_moved_attributes = [ - MovedAttribute("URLError", "urllib2", "urllib.error"), - MovedAttribute("HTTPError", "urllib2", "urllib.error"), - MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), -] -for attr in _urllib_error_moved_attributes: - setattr(Module_six_moves_urllib_error, attr.name, attr) -del attr - -Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes - -_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), - "moves.urllib_error", "moves.urllib.error") - - -class Module_six_moves_urllib_request(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_request""" - - -_urllib_request_moved_attributes = [ - MovedAttribute("urlopen", "urllib2", "urllib.request"), - MovedAttribute("install_opener", "urllib2", "urllib.request"), - MovedAttribute("build_opener", "urllib2", "urllib.request"), - MovedAttribute("pathname2url", "urllib", "urllib.request"), - MovedAttribute("url2pathname", "urllib", "urllib.request"), - MovedAttribute("getproxies", "urllib", "urllib.request"), - MovedAttribute("Request", "urllib2", "urllib.request"), - MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), - MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), - MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), - MovedAttribute("BaseHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), - MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), - MovedAttribute("FileHandler", "urllib2", "urllib.request"), - MovedAttribute("FTPHandler", "urllib2", "urllib.request"), - MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), - MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), - MovedAttribute("urlretrieve", "urllib", "urllib.request"), - MovedAttribute("urlcleanup", "urllib", "urllib.request"), - MovedAttribute("URLopener", "urllib", "urllib.request"), - MovedAttribute("FancyURLopener", "urllib", "urllib.request"), - MovedAttribute("proxy_bypass", "urllib", "urllib.request"), - MovedAttribute("parse_http_list", "urllib2", "urllib.request"), - MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), -] -for attr in _urllib_request_moved_attributes: - setattr(Module_six_moves_urllib_request, attr.name, attr) -del attr - -Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes - -_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), - "moves.urllib_request", "moves.urllib.request") - - -class Module_six_moves_urllib_response(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_response""" - - -_urllib_response_moved_attributes = [ - MovedAttribute("addbase", "urllib", "urllib.response"), - MovedAttribute("addclosehook", "urllib", "urllib.response"), - MovedAttribute("addinfo", "urllib", "urllib.response"), - MovedAttribute("addinfourl", "urllib", "urllib.response"), -] -for attr in _urllib_response_moved_attributes: - setattr(Module_six_moves_urllib_response, attr.name, attr) -del attr - -Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes - -_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), - "moves.urllib_response", "moves.urllib.response") - - -class Module_six_moves_urllib_robotparser(_LazyModule): - - """Lazy loading of moved objects in six.moves.urllib_robotparser""" - - -_urllib_robotparser_moved_attributes = [ - MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), -] -for attr in _urllib_robotparser_moved_attributes: - setattr(Module_six_moves_urllib_robotparser, attr.name, attr) -del attr - -Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes - -_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), - "moves.urllib_robotparser", "moves.urllib.robotparser") - - -class Module_six_moves_urllib(types.ModuleType): - - """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - __path__ = [] # mark as package - parse = _importer._get_module("moves.urllib_parse") - error = _importer._get_module("moves.urllib_error") - request = _importer._get_module("moves.urllib_request") - response = _importer._get_module("moves.urllib_response") - robotparser = _importer._get_module("moves.urllib_robotparser") - - def __dir__(self): - return ['parse', 'error', 'request', 'response', 'robotparser'] - -_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), - "moves.urllib") - - -def add_move(move): - """Add an item to six.moves.""" - setattr(_MovedItems, move.name, move) - - -def remove_move(name): - """Remove item from six.moves.""" - try: - delattr(_MovedItems, name) - except AttributeError: - try: - del moves.__dict__[name] - except KeyError: - raise AttributeError("no such move, %r" % (name,)) - - -if PY3: - _meth_func = "__func__" - _meth_self = "__self__" - - _func_closure = "__closure__" - _func_code = "__code__" - _func_defaults = "__defaults__" - _func_globals = "__globals__" -else: - _meth_func = "im_func" - _meth_self = "im_self" - - _func_closure = "func_closure" - _func_code = "func_code" - _func_defaults = "func_defaults" - _func_globals = "func_globals" - - -try: - advance_iterator = next -except NameError: - def advance_iterator(it): - return it.next() -next = advance_iterator - - -try: - callable = callable -except NameError: - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) - - -if PY3: - def get_unbound_function(unbound): - return unbound - - create_bound_method = types.MethodType - - def create_unbound_method(func, cls): - return func - - Iterator = object -else: - def get_unbound_function(unbound): - return unbound.im_func - - def create_bound_method(func, obj): - return types.MethodType(func, obj, obj.__class__) - - def create_unbound_method(func, cls): - return types.MethodType(func, None, cls) - - class Iterator(object): - - def next(self): - return type(self).__next__(self) - - callable = callable -_add_doc(get_unbound_function, - """Get the function out of a possibly unbound function""") - - -get_method_function = operator.attrgetter(_meth_func) -get_method_self = operator.attrgetter(_meth_self) -get_function_closure = operator.attrgetter(_func_closure) -get_function_code = operator.attrgetter(_func_code) -get_function_defaults = operator.attrgetter(_func_defaults) -get_function_globals = operator.attrgetter(_func_globals) - - -if PY3: - def iterkeys(d, **kw): - return iter(d.keys(**kw)) - - def itervalues(d, **kw): - return iter(d.values(**kw)) - - def iteritems(d, **kw): - return iter(d.items(**kw)) - - def iterlists(d, **kw): - return iter(d.lists(**kw)) - - viewkeys = operator.methodcaller("keys") - - viewvalues = operator.methodcaller("values") - - viewitems = operator.methodcaller("items") -else: - def iterkeys(d, **kw): - return d.iterkeys(**kw) - - def itervalues(d, **kw): - return d.itervalues(**kw) - - def iteritems(d, **kw): - return d.iteritems(**kw) - - def iterlists(d, **kw): - return d.iterlists(**kw) - - viewkeys = operator.methodcaller("viewkeys") - - viewvalues = operator.methodcaller("viewvalues") - - viewitems = operator.methodcaller("viewitems") - -_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") -_add_doc(itervalues, "Return an iterator over the values of a dictionary.") -_add_doc(iteritems, - "Return an iterator over the (key, value) pairs of a dictionary.") -_add_doc(iterlists, - "Return an iterator over the (key, [values]) pairs of a dictionary.") - - -if PY3: - def b(s): - return s.encode("latin-1") - - def u(s): - return s - unichr = chr - import struct - int2byte = struct.Struct(">B").pack - del struct - byte2int = operator.itemgetter(0) - indexbytes = operator.getitem - iterbytes = iter - import io - StringIO = io.StringIO - BytesIO = io.BytesIO - _assertCountEqual = "assertCountEqual" - if sys.version_info[1] <= 1: - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" - else: - _assertRaisesRegex = "assertRaisesRegex" - _assertRegex = "assertRegex" -else: - def b(s): - return s - # Workaround for standalone backslash - - def u(s): - return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") - unichr = unichr - int2byte = chr - - def byte2int(bs): - return ord(bs[0]) - - def indexbytes(buf, i): - return ord(buf[i]) - iterbytes = functools.partial(itertools.imap, ord) - import StringIO - StringIO = BytesIO = StringIO.StringIO - _assertCountEqual = "assertItemsEqual" - _assertRaisesRegex = "assertRaisesRegexp" - _assertRegex = "assertRegexpMatches" -_add_doc(b, """Byte literal""") -_add_doc(u, """Text literal""") - - -def assertCountEqual(self, *args, **kwargs): - return getattr(self, _assertCountEqual)(*args, **kwargs) - - -def assertRaisesRegex(self, *args, **kwargs): - return getattr(self, _assertRaisesRegex)(*args, **kwargs) - - -def assertRegex(self, *args, **kwargs): - return getattr(self, _assertRegex)(*args, **kwargs) - - -if PY3: - exec_ = getattr(moves.builtins, "exec") - - def reraise(tp, value, tb=None): - try: - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - finally: - value = None - tb = None - -else: - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - exec_("""def reraise(tp, value, tb=None): - try: - raise tp, value, tb - finally: - tb = None -""") - - -if sys.version_info[:2] == (3, 2): - exec_("""def raise_from(value, from_value): - try: - if from_value is None: - raise value - raise value from from_value - finally: - value = None -""") -elif sys.version_info[:2] > (3, 2): - exec_("""def raise_from(value, from_value): - try: - raise value from from_value - finally: - value = None -""") -else: - def raise_from(value, from_value): - raise value - - -print_ = getattr(moves.builtins, "print", None) -if print_ is None: - def print_(*args, **kwargs): - """The new-style print function for Python 2.4 and 2.5.""" - fp = kwargs.pop("file", sys.stdout) - if fp is None: - return - - def write(data): - if not isinstance(data, basestring): - data = str(data) - # If the file has an encoding, encode unicode with it. - if (isinstance(fp, file) and - isinstance(data, unicode) and - fp.encoding is not None): - errors = getattr(fp, "errors", None) - if errors is None: - errors = "strict" - data = data.encode(fp.encoding, errors) - fp.write(data) - want_unicode = False - sep = kwargs.pop("sep", None) - if sep is not None: - if isinstance(sep, unicode): - want_unicode = True - elif not isinstance(sep, str): - raise TypeError("sep must be None or a string") - end = kwargs.pop("end", None) - if end is not None: - if isinstance(end, unicode): - want_unicode = True - elif not isinstance(end, str): - raise TypeError("end must be None or a string") - if kwargs: - raise TypeError("invalid keyword arguments to print()") - if not want_unicode: - for arg in args: - if isinstance(arg, unicode): - want_unicode = True - break - if want_unicode: - newline = unicode("\n") - space = unicode(" ") - else: - newline = "\n" - space = " " - if sep is None: - sep = space - if end is None: - end = newline - for i, arg in enumerate(args): - if i: - write(sep) - write(arg) - write(end) -if sys.version_info[:2] < (3, 3): - _print = print_ - - def print_(*args, **kwargs): - fp = kwargs.get("file", sys.stdout) - flush = kwargs.pop("flush", False) - _print(*args, **kwargs) - if flush and fp is not None: - fp.flush() - -_add_doc(reraise, """Reraise an exception.""") - -if sys.version_info[0:2] < (3, 4): - def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, - updated=functools.WRAPPER_UPDATES): - def wrapper(f): - f = functools.wraps(wrapped, assigned, updated)(f) - f.__wrapped__ = wrapped - return f - return wrapper -else: - wraps = functools.wraps - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - # This requires a bit of explanation: the basic idea is to make a dummy - # metaclass for one level of class instantiation that replaces itself with - # the actual metaclass. - class metaclass(type): - - def __new__(cls, name, this_bases, d): - return meta(name, bases, d) - - @classmethod - def __prepare__(cls, name, this_bases): - return meta.__prepare__(name, bases) - return type.__new__(metaclass, 'temporary_class', (), {}) - - -def add_metaclass(metaclass): - """Class decorator for creating a class with a metaclass.""" - def wrapper(cls): - orig_vars = cls.__dict__.copy() - slots = orig_vars.get('__slots__') - if slots is not None: - if isinstance(slots, str): - slots = [slots] - for slots_var in slots: - orig_vars.pop(slots_var) - orig_vars.pop('__dict__', None) - orig_vars.pop('__weakref__', None) - if hasattr(cls, '__qualname__'): - orig_vars['__qualname__'] = cls.__qualname__ - return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper - - -def ensure_binary(s, encoding='utf-8', errors='strict'): - """Coerce **s** to six.binary_type. - - For Python 2: - - `unicode` -> encoded to `str` - - `str` -> `str` - - For Python 3: - - `str` -> encoded to `bytes` - - `bytes` -> `bytes` - """ - if isinstance(s, text_type): - return s.encode(encoding, errors) - elif isinstance(s, binary_type): - return s - else: - raise TypeError("not expecting type '%s'" % type(s)) - - -def ensure_str(s, encoding='utf-8', errors='strict'): - """Coerce *s* to `str`. - - For Python 2: - - `unicode` -> encoded to `str` - - `str` -> `str` - - For Python 3: - - `str` -> `str` - - `bytes` -> decoded to `str` - """ - if not isinstance(s, (text_type, binary_type)): - raise TypeError("not expecting type '%s'" % type(s)) - if PY2 and isinstance(s, text_type): - s = s.encode(encoding, errors) - elif PY3 and isinstance(s, binary_type): - s = s.decode(encoding, errors) - return s - - -def ensure_text(s, encoding='utf-8', errors='strict'): - """Coerce *s* to six.text_type. - - For Python 2: - - `unicode` -> `unicode` - - `str` -> `unicode` - - For Python 3: - - `str` -> `str` - - `bytes` -> decoded to `str` - """ - if isinstance(s, binary_type): - return s.decode(encoding, errors) - elif isinstance(s, text_type): - return s - else: - raise TypeError("not expecting type '%s'" % type(s)) - - - -def python_2_unicode_compatible(klass): - """ - A decorator that defines __unicode__ and __str__ methods under Python 2. - Under Python 3 it does nothing. - - To support Python 2 and 3 with a single code base, define a __str__ method - returning text and apply this decorator to the class. - """ - if PY2: - if '__str__' not in klass.__dict__: - raise ValueError("@python_2_unicode_compatible cannot be applied " - "to %s because it doesn't define __str__()." % - klass.__name__) - klass.__unicode__ = klass.__str__ - klass.__str__ = lambda self: self.__unicode__().encode('utf-8') - return klass - - -# Complete the moves implementation. -# This code is at the end of this module to speed up module loading. -# Turn this module into a package. -__path__ = [] # required for PEP 302 and PEP 451 -__package__ = __name__ # see PEP 366 @ReservedAssignment -if globals().get("__spec__") is not None: - __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable -# Remove other six meta path importers, since they cause problems. This can -# happen if six is removed from sys.modules and then reloaded. (Setuptools does -# this for some reason.) -if sys.meta_path: - for i, importer in enumerate(sys.meta_path): - # Here's some real nastiness: Another "instance" of the six module might - # be floating around. Therefore, we can't use isinstance() to check for - # the six meta path importer, since the other six instance will have - # inserted an importer with different class. - if (type(importer).__name__ == "_SixMetaPathImporter" and - importer.name == __name__): - del sys.meta_path[i] - break - del i, importer -# Finally, add the importer to the meta path import hook. -sys.meta_path.append(_importer) diff --git a/demo/AUI_DockingWindowMgr.py b/demo/AUI_DockingWindowMgr.py index 0faca4f7..7b62face 100644 --- a/demo/AUI_DockingWindowMgr.py +++ b/demo/AUI_DockingWindowMgr.py @@ -5,7 +5,7 @@ import wx.grid import wx.html import wx.aui as aui -from six import BytesIO +from io import BytesIO ID_CreateTree = wx.NewIdRef() ID_CreateGrid = wx.NewIdRef() diff --git a/demo/ArtProvider.py b/demo/ArtProvider.py index b890894e..b5a8fa1f 100644 --- a/demo/ArtProvider.py +++ b/demo/ArtProvider.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # Tags: phoenix-port, py3-port -from six import BytesIO +from io import BytesIO import wx diff --git a/demo/ImageFromStream.py b/demo/ImageFromStream.py index f428265e..5a490c5f 100644 --- a/demo/ImageFromStream.py +++ b/demo/ImageFromStream.py @@ -1,7 +1,7 @@ #!/usr/bin/env python # Tags: phoenix-port, py3-port -from six import BytesIO +from io import BytesIO import wx diff --git a/demo/Main.py b/demo/Main.py index db956362..0c5ea6ee 100644 --- a/demo/Main.py +++ b/demo/Main.py @@ -54,6 +54,7 @@ import sys, os, time, traceback import re import shutil +from io import BytesIO from threading import Thread @@ -66,8 +67,6 @@ from wx.adv import TaskBarIcon as TaskBarIcon from wx.adv import SplashScreen as SplashScreen import wx.lib.mixins.inspection -import six -from six import exec_, BytesIO from six.moves import cPickle from six.moves import urllib @@ -417,10 +416,7 @@ class InternetThread(Thread): try: url = _docsURL % ReplaceCapitals(self.selectedClass) with urllib.request.urlopen(url) as fid: - if six.PY2: - originalText = fid.read() - else: - originalText = fid.read().decode("utf-8") + originalText = fid.read().decode("utf-8") text = RemoveHTMLTags(originalText).split("\n") data = FindWindowStyles(text, originalText, self.selectedClass) @@ -962,9 +958,6 @@ def SearchDemo(name, keyword): with open(GetOriginalFilename(name), "rt") as fid: fullText = fid.read() - if six.PY2: - fullText = fullText.decode("iso-8859-1") - if fullText.find(keyword) >= 0: return True @@ -1075,10 +1068,9 @@ class DemoModules(object): self.modules = [[dict(), "" , "" , "" , None], [dict(), "" , "" , "" , None]] - getcwd = os.getcwd if six.PY3 else os.getcwdu for i in [modOriginal, modModified]: self.modules[i][0]['__file__'] = \ - os.path.join(getcwd(), GetOriginalFilename(name)) + os.path.join(os.getcwd(), GetOriginalFilename(name)) # load original module self.LoadFromFile(modOriginal, GetOriginalFilename(name)) @@ -1102,12 +1094,10 @@ class DemoModules(object): if self.name != __name__: source = self.modules[modID][1] description = self.modules[modID][2] - if six.PY2: - description = description.encode(sys.getfilesystemencoding()) try: code = compile(source, description, "exec") - exec_(code, self.modules[modID][0]) + exec(code, self.modules[modID][0]) except: self.modules[modID][4] = DemoError(sys.exc_info()) self.modules[modID][0] = None @@ -2228,10 +2218,6 @@ class wxPythonDemo(wx.Frame): self.pickledData[itemText] = data - if six.PY2: - # TODO: verify that this encoding is correct - text = text.decode('iso8859_1') - self.StopDownload() self.ovr.SetPage(text) #print("load time: ", time.time() - start) diff --git a/demo/MimeTypesManager.py b/demo/MimeTypesManager.py index 79bc3abe..ca14ff10 100644 --- a/demo/MimeTypesManager.py +++ b/demo/MimeTypesManager.py @@ -18,8 +18,7 @@ import images # helper function to make sure we don't convert unicode objects to strings # or vice versa when converting lists and None values to text. -import six -convert = six.text_type +convert = str #---------------------------------------------------------------------------- diff --git a/demo/PropertyGrid.py b/demo/PropertyGrid.py index fbef29e3..3e87798c 100644 --- a/demo/PropertyGrid.py +++ b/demo/PropertyGrid.py @@ -9,7 +9,6 @@ import wx import wx.adv import wx.propgrid as wxpg -from six import exec_ _ = wx.GetTranslation @@ -870,7 +869,7 @@ class TestPanel( wx.Panel ): sandbox = {'obj':ValueObject(), 'wx':wx, 'datetime':datetime} - exec_(dlg.tc.GetValue(), sandbox) + exec(dlg.tc.GetValue(), sandbox) t_start = time.time() #print(sandbox['obj'].__dict__) self.pg.SetPropertyValues(sandbox['obj']) @@ -917,7 +916,7 @@ class TestPanel( wx.Panel ): with MemoDialog(self,"Enter Content for Object Used for AutoFill",default_object_content1) as dlg: if dlg.ShowModal() == wx.ID_OK: sandbox = {'object':ValueObject(),'wx':wx} - exec_(dlg.tc.GetValue(), sandbox) + exec(dlg.tc.GetValue(), sandbox) t_start = time.time() self.pg.AutoFill(sandbox['object']) t_end = time.time() diff --git a/demo/RichTextCtrl.py b/demo/RichTextCtrl.py index 7ac6b1cb..b88502af 100644 --- a/demo/RichTextCtrl.py +++ b/demo/RichTextCtrl.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from six import BytesIO +from io import BytesIO import wx import wx.richtext as rt diff --git a/demo/SVGImage_Bitmap.py b/demo/SVGImage_Bitmap.py index 5284291d..0b7c51d4 100644 --- a/demo/SVGImage_Bitmap.py +++ b/demo/SVGImage_Bitmap.py @@ -2,7 +2,6 @@ import sys import os import glob -import six import wx from wx.svg import SVGimage @@ -26,8 +25,6 @@ class SVGBitmapDisplay(wx.Panel): def UpdateSVG(self, svg_filename): - if six.PY2 and isinstance(svg_filename, unicode): - svg_filename = svg_filename.encode(sys.getfilesystemencoding()) img = SVGimage.CreateFromFile(svg_filename) bmp = img.ConvertToScaledBitmap(self.bmp_size, self) self.statbmp.SetBitmap(bmp) diff --git a/demo/SVGImage_Render.py b/demo/SVGImage_Render.py index 579eb5f2..5c21cf22 100644 --- a/demo/SVGImage_Render.py +++ b/demo/SVGImage_Render.py @@ -2,7 +2,6 @@ import sys import os import glob -import six import wx from wx.svg import SVGimage @@ -26,8 +25,6 @@ class SVGRenderPanel(wx.Panel): def SetSVGFile(self, svg_filename): - if six.PY2 and isinstance(svg_filename, unicode): - svg_filename = svg_filename.encode(sys.getfilesystemencoding()) self._img = SVGimage.CreateFromFile(svg_filename) self.Refresh() diff --git a/demo/agw/FoldPanelBar.py b/demo/agw/FoldPanelBar.py index 7d191bc5..62201e5c 100644 --- a/demo/agw/FoldPanelBar.py +++ b/demo/agw/FoldPanelBar.py @@ -5,8 +5,7 @@ import wx import wx.adv import os import sys - -from six import BytesIO +from io import BytesIO try: dirName = os.path.dirname(os.path.abspath(__file__)) diff --git a/demo/agw/HyperTreeList.py b/demo/agw/HyperTreeList.py index c88e6729..c00a8125 100644 --- a/demo/agw/HyperTreeList.py +++ b/demo/agw/HyperTreeList.py @@ -4,15 +4,13 @@ import os import string import random +import sys +from io import BytesIO import wx import wx.lib.colourselect as csel import wx.lib.colourutils as cutils -import sys - -from six import BytesIO - try: dirName = os.path.dirname(os.path.abspath(__file__)) except: diff --git a/demo/agw/Windows7Explorer_Contents.py b/demo/agw/Windows7Explorer_Contents.py index b23df0e1..c24db908 100644 --- a/demo/agw/Windows7Explorer_Contents.py +++ b/demo/agw/Windows7Explorer_Contents.py @@ -3,7 +3,6 @@ import sys import os import wx -import six import time import datetime import operator @@ -27,12 +26,7 @@ except ImportError: # if it's not there locally, try the wxPython lib. bitmapDir = os.path.join(dirName, 'bitmaps') sys.path.append(os.path.split(dirName)[0]) -# helper function to make sure we don't convert unicode objects to strings -# or vice versa when converting lists and None values to text. convert = str -if six.PY2: - if 'unicode' in wx.PlatformInfo: - convert = unicode def FormatFileSize(size): diff --git a/etg/config.py b/etg/config.py index 6a012223..c2bc87c8 100644 --- a/etg/config.py +++ b/etg/config.py @@ -62,10 +62,7 @@ def run(): return rv; """) c.addPyMethod('ReadInt', '(self, key, defaultVal=0)', body="""\ - import six rv = self._cpp_ReadInt(key, defaultVal) - if six.PY2: - rv = int(rv) return rv """) diff --git a/etg/listctrl.py b/etg/listctrl.py index dc531a3e..2c76b003 100644 --- a/etg/listctrl.py +++ b/etg/listctrl.py @@ -316,10 +316,9 @@ def run(): sequence with an item for each column''', body="""\ if len(entry): - from six import text_type - pos = self.InsertItem(self.GetItemCount(), text_type(entry[0])) + pos = self.InsertItem(self.GetItemCount(), str(entry[0])) for i in range(1, len(entry)): - self.SetItem(pos, i, text_type(entry[i])) + self.SetItem(pos, i, str(entry[i])) return pos """) diff --git a/etg/wxdatetime.py b/etg/wxdatetime.py index 709f60f6..eb18c8ed 100644 --- a/etg/wxdatetime.py +++ b/etg/wxdatetime.py @@ -254,20 +254,16 @@ def run(): c.addPyMethod('__repr__', '(self)', """\ - from six import PY2 if self.IsValid(): f = self.Format() - if PY2: f = f.encode('utf-8') return '' % f else: return '' """) c.addPyMethod('__str__', '(self)', """\ - from six import PY2 if self.IsValid(): f = self.Format() - if PY2: f = f.encode('utf-8') return f else: return "INVALID DateTime" diff --git a/samples/doodle/superdoodle.py b/samples/doodle/superdoodle.py index 0b3d0932..feff7ff2 100644 --- a/samples/doodle/superdoodle.py +++ b/samples/doodle/superdoodle.py @@ -11,8 +11,7 @@ implemented using an wx.html.HtmlWindow. import sys import os - -from six.moves import cPickle as pickle +import pickle import wx import wx.html diff --git a/samples/floatcanvas/DrawBot.py b/samples/floatcanvas/DrawBot.py index 52ea41e0..5bb2a539 100644 --- a/samples/floatcanvas/DrawBot.py +++ b/samples/floatcanvas/DrawBot.py @@ -14,7 +14,6 @@ I think it's easier with FloatCavnas, and you get zoomign and scrolling to boot! """ import wx -from six import moves from math import * try: # see if there is a local FloatCanvas to use @@ -54,7 +53,7 @@ class DrawFrame(wx.Frame): Canvas = self.Canvas phi = (sqrt(5) + 1)/2 - 1 oradius = 10.0 - for i in moves.xrange(720): + for i in range(720): radius = 1.5 * oradius * sin(i * pi/720) Color = (255*(i / 720.), 255*( i / 720.), 255 * 0.25) x = oradius + 0.25*i*cos(phi*i*2*pi) diff --git a/samples/html2/webview_sample.py b/samples/html2/webview_sample.py index 22b6489c..61fbf776 100644 --- a/samples/html2/webview_sample.py +++ b/samples/html2/webview_sample.py @@ -1,6 +1,6 @@ import sys import os -from six import BytesIO +from io import BytesIO import wx import wx.html2 as webview diff --git a/samples/printing/printing.py b/samples/printing/printing.py index 8af9a05e..bc63744c 100644 --- a/samples/printing/printing.py +++ b/samples/printing/printing.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import wx import os diff --git a/samples/roses/clroses.py b/samples/roses/clroses.py index f25ac93b..b6a9ca64 100644 --- a/samples/roses/clroses.py +++ b/samples/roses/clroses.py @@ -36,8 +36,6 @@ # ideal Roses program should be, however, callers are welcome to assert their # independence, override defaults, ignore features, etc. -from __future__ import print_function - from math import sin, cos, pi # Rose class knows about: diff --git a/samples/roses/wxroses.py b/samples/roses/wxroses.py index 645f56aa..d6426bff 100644 --- a/samples/roses/wxroses.py +++ b/samples/roses/wxroses.py @@ -68,8 +68,6 @@ # control the display (without blocking the user's control) would be pretty # straightforward. -from __future__ import print_function - import wx import clroses import wx.lib.colourselect as cs diff --git a/samples/simple/events.py b/samples/simple/events.py index 112875bd..06ecb0d3 100644 --- a/samples/simple/events.py +++ b/samples/simple/events.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import wx print(wx.version()) diff --git a/sphinxtools/modulehunter.py b/sphinxtools/modulehunter.py index 6224c896..f53ad678 100644 --- a/sphinxtools/modulehunter.py +++ b/sphinxtools/modulehunter.py @@ -22,18 +22,11 @@ from .librarydescription import Method, Property, Attribute from . import inheritance -from .utilities import isPython3, PickleFile +from .utilities import PickleFile from .constants import object_types, EXCLUDED_ATTRS, MODULE_TO_ICON from .constants import CONSTANT_RE -if sys.version_info < (3,): - reload(sys) - sys.setdefaultencoding('utf-8') - -if isPython3(): - MethodTypes = (classmethod, types.MethodType, types.ClassMethodDescriptorType) -else: - MethodTypes = (classmethod, types.MethodType) +MethodTypes = (classmethod, types.MethodType, types.ClassMethodDescriptorType) try: import wx diff --git a/unittests/test_arraystring.py b/unittests/test_arraystring.py index bb7a80c9..cdbb4728 100644 --- a/unittests/test_arraystring.py +++ b/unittests/test_arraystring.py @@ -1,24 +1,16 @@ import unittest import wx -import six #--------------------------------------------------------------------------- -if not six.PY3: - alt = unicode -else: - def alt(s): - return bytes(s, 'utf-8') - - class ArrayString(unittest.TestCase): if hasattr(wx, 'testArrayStringTypemap'): def test_ArrayStringTypemaps(self): # basic conversion of list or tuples of strings - seqList = ['a', alt('b'), 'hello world'] + seqList = ['a', b'b', 'hello world'] self.assertEqual(wx.testArrayStringTypemap(seqList), ['a', 'b', 'hello world']) - seqTuple = ('a', alt('b'), 'hello world') + seqTuple = ('a', b'b', 'hello world') self.assertEqual(wx.testArrayStringTypemap(seqTuple), ['a', 'b', 'hello world']) def test_ArrayStringTypemapErrors(self): @@ -26,7 +18,7 @@ class ArrayString(unittest.TestCase): with self.assertRaises(TypeError): wx.testArrayStringTypemap("STRING sequence") with self.assertRaises(TypeError): - wx.testArrayStringTypemap(alt("ALT sequence")) + wx.testArrayStringTypemap(b"ALT sequence") with self.assertRaises(TypeError): wx.testArrayStringTypemap(["list", "with", "non-string", "items", 123]) diff --git a/unittests/test_bitmap.py b/unittests/test_bitmap.py index 72132e31..4cab3d0f 100644 --- a/unittests/test_bitmap.py +++ b/unittests/test_bitmap.py @@ -2,7 +2,6 @@ import unittest from unittests import wtc import wx import os -import six pngFile = os.path.join(os.path.dirname(__file__), 'toucan.png') @@ -58,10 +57,7 @@ class BitmapTests(wtc.WidgetTestCase): self.assertTrue( not b1.IsOk() ) b2 = wx.Bitmap(5, 10, 24) self.assertTrue( b2.IsOk() ) - if six.PY3: - self.assertTrue( b2.__bool__() == b2.IsOk() ) - else: - self.assertTrue( b2.__nonzero__() == b2.IsOk() ) + self.assertTrue( b2.__bool__() == b2.IsOk() ) # check that the __nonzero__ method can be used with if statements nzcheck = False diff --git a/unittests/test_cmndata.py b/unittests/test_cmndata.py index 8bba2b77..c8d13c68 100644 --- a/unittests/test_cmndata.py +++ b/unittests/test_cmndata.py @@ -1,7 +1,6 @@ import unittest from unittests import wtc import wx -import six #--------------------------------------------------------------------------- @@ -37,14 +36,9 @@ class cmndata_tests(wtc.WidgetTestCase): pd = wx.PrintData() pdd = wx.PrintDialogData() - if six.PY3: - psdd.__bool__() - pd.__bool__() - pdd.__bool__() - else: - psdd.__nonzero__() - pd.__nonzero__() - pdd.__nonzero__() + psdd.__bool__() + pd.__bool__() + pdd.__bool__() def test_PD_PaperSize(self): diff --git a/unittests/test_cursor.py b/unittests/test_cursor.py index 6bc10026..63852b3e 100644 --- a/unittests/test_cursor.py +++ b/unittests/test_cursor.py @@ -1,7 +1,6 @@ import unittest from unittests import wtc import wx -import six import os pngFile = os.path.join(os.path.dirname(__file__), 'pointy.png') @@ -70,10 +69,7 @@ class CursorTests(wtc.WidgetTestCase): c2 = wx.Cursor(wx.CURSOR_ARROW) self.assertTrue( c2.IsOk() ) - if six.PY3: - self.assertTrue( c2.__bool__() == c2.IsOk() ) - else: - self.assertTrue( c2.__nonzero__() == c2.IsOk() ) + self.assertTrue( c2.__bool__() == c2.IsOk() ) # check that the __nonzero__ method can be used with if statements nzcheck = False diff --git a/unittests/test_image.py b/unittests/test_image.py index fb3f6202..eaf28257 100644 --- a/unittests/test_image.py +++ b/unittests/test_image.py @@ -1,8 +1,7 @@ import unittest from unittests import wtc import wx -import six -from six import BytesIO as FileLikeObject +from io import BytesIO as FileLikeObject import os @@ -136,20 +135,12 @@ class image_Tests(wtc.WidgetTestCase): self.assertTrue(img.IsOk()) data = img.GetDataBuffer() self.assertTrue(isinstance(data, memoryview)) - if six.PY2: - data[0] = b'1' - data[1] = b'2' - data[2] = b'3' - self.assertEqual(ord('1'), img.GetRed(0,0)) - self.assertEqual(ord('2'), img.GetGreen(0,0)) - self.assertEqual(ord('3'), img.GetBlue(0,0)) - else: - data[0] = 1 - data[1] = 2 - data[2] = 3 - self.assertEqual(1, img.GetRed(0,0)) - self.assertEqual(2, img.GetGreen(0,0)) - self.assertEqual(3, img.GetBlue(0,0)) + data[0] = 1 + data[1] = 2 + data[2] = 3 + self.assertEqual(1, img.GetRed(0,0)) + self.assertEqual(2, img.GetGreen(0,0)) + self.assertEqual(3, img.GetBlue(0,0)) def test_imageGetAlphaDataBuffer(self): @@ -159,20 +150,12 @@ class image_Tests(wtc.WidgetTestCase): self.assertTrue(img.IsOk()) data = img.GetAlphaBuffer() self.assertTrue(isinstance(data, memoryview)) - if six.PY2: - data[0] = b'1' - data[1] = b'2' - data[2] = b'3' - self.assertEqual(ord('1'), img.GetAlpha(0,0)) - self.assertEqual(ord('2'), img.GetAlpha(1,0)) - self.assertEqual(ord('3'), img.GetAlpha(2,0)) - else: - data[0] = 1 - data[1] = 2 - data[2] = 3 - self.assertEqual(1, img.GetAlpha(0,0)) - self.assertEqual(2, img.GetAlpha(1,0)) - self.assertEqual(3, img.GetAlpha(2,0)) + data[0] = 1 + data[1] = 2 + data[2] = 3 + self.assertEqual(1, img.GetAlpha(0,0)) + self.assertEqual(2, img.GetAlpha(1,0)) + self.assertEqual(3, img.GetAlpha(2,0)) def test_imageSetDataBuffer1(self): diff --git a/unittests/test_lib_cdate.py b/unittests/test_lib_cdate.py index 02acd124..c7825ee6 100644 --- a/unittests/test_lib_cdate.py +++ b/unittests/test_lib_cdate.py @@ -1,7 +1,6 @@ import unittest from unittests import wtc import wx.lib.CDate as cdate -import six import datetime class lib_cdate_Tests(wtc.WidgetTestCase): diff --git a/unittests/test_lib_pubsub_defaultlog.py b/unittests/test_lib_pubsub_defaultlog.py index 6d952568..f8208870 100644 --- a/unittests/test_lib_pubsub_defaultlog.py +++ b/unittests/test_lib_pubsub_defaultlog.py @@ -7,10 +7,10 @@ """ import unittest +from io import StringIO from unittests import wtc from wx.lib.pubsub.utils import notification -from six import StringIO #--------------------------------------------------------------------------- diff --git a/unittests/test_lib_pubsub_listener.py b/unittests/test_lib_pubsub_listener.py index 2f71fe7c..95e17ab5 100644 --- a/unittests/test_lib_pubsub_listener.py +++ b/unittests/test_lib_pubsub_listener.py @@ -5,7 +5,6 @@ """ -import six import unittest from unittests import wtc @@ -195,9 +194,6 @@ class lib_pubsub_ArgsInfo(wtc.PubsubTestCase): def tmpFn(self): pass Listener( DOA.tmpFn, ArgsInfoMock() ) - # Py3 doesn't have unbound methods so this won't throw a ValueError - if not six.PY3: - self.assertRaises(ValueError, getListener1) # test DOA of tmp callable: def getListener2(): diff --git a/unittests/test_lib_pubsub_notify.py b/unittests/test_lib_pubsub_notify.py index 5128ca3f..4e7bd1df 100644 --- a/unittests/test_lib_pubsub_notify.py +++ b/unittests/test_lib_pubsub_notify.py @@ -22,7 +22,7 @@ class lib_pubsub_Notify(wtc.PubsubTestCase): from wx.lib.pubsub.utils.notification import useNotifyByWriteFile def captureStdout(): - from six import StringIO + from io import StringIO capture = StringIO() useNotifyByWriteFile( fileObj = capture ) return capture diff --git a/unittests/test_lib_pubsub_notify4.py b/unittests/test_lib_pubsub_notify4.py index 8d79ba8c..11d11149 100644 --- a/unittests/test_lib_pubsub_notify4.py +++ b/unittests/test_lib_pubsub_notify4.py @@ -9,7 +9,6 @@ import unittest from unittests import wtc -import six from difflib import ndiff, unified_diff, context_diff @@ -45,7 +44,7 @@ class lib_pubsub_NotifyN(wtc.PubsubTestCase): self.pub.setNotificationFlags(all=True) def verify(**ref): - for key, val in six.iteritems(notifiee.counts): + for key, val in notifiee.counts.items(): if key in ref: self.assertEqual(val, ref[key], "\n%s\n%s" % (notifiee.counts, ref) ) else: diff --git a/unittests/test_lib_pubsub_topicmgr.py b/unittests/test_lib_pubsub_topicmgr.py index da0da080..9ccdec55 100644 --- a/unittests/test_lib_pubsub_topicmgr.py +++ b/unittests/test_lib_pubsub_topicmgr.py @@ -359,7 +359,7 @@ r'''\-- Topic "a2" topicMgr.getOrCreateTopic('a2.b.a') topicMgr.getOrCreateTopic('a2.b.b') - from six import StringIO + from io import StringIO buffer = StringIO() printTreeDocs(rootTopic=root, width=70, fileObj=buffer) self.assertEqual( buffer.getvalue(), self.expectedOutput ) diff --git a/unittests/test_pgvariant.py b/unittests/test_pgvariant.py index 686698c1..2ca2de31 100644 --- a/unittests/test_pgvariant.py +++ b/unittests/test_pgvariant.py @@ -3,8 +3,6 @@ from unittests import wtc import wx import wx.propgrid as pg -import six - #--------------------------------------------------------------------------- class pgvariant_Tests(wtc.WidgetTestCase): diff --git a/unittests/test_stream.py b/unittests/test_stream.py index e19042d5..18751a8c 100644 --- a/unittests/test_stream.py +++ b/unittests/test_stream.py @@ -1,8 +1,7 @@ import unittest from unittests import wtc import wx -import six -from six import BytesIO as FileLikeObject +from io import BytesIO as FileLikeObject import os diff --git a/unittests/test_string.py b/unittests/test_string.py index e75dc2bf..a2406ed6 100644 --- a/unittests/test_string.py +++ b/unittests/test_string.py @@ -1,6 +1,5 @@ import unittest import wx -import six from unittests import wtc #--------------------------------------------------------------------------- @@ -10,57 +9,6 @@ from unittests import wtc class String(unittest.TestCase): if hasattr(wx, 'testStringTypemap'): - if not six.PY3: - def test_StringTypemapsPy2(self): - utf = '\xc3\xa9l\xc3\xa9phant' # utf-8 string - uni = utf.decode('utf-8') # convert to unicode - iso = uni.encode('iso-8859-1') # make a string with a different encoding - - - # wx.testStringTypemap() will accept a parameter that - # is a Unicode object or an 'ascii' or 'utf-8' string object, - # which will then be converted to a wxString. The return - # value is a Unicode object that has been converted from a - # wxString that is a copy of the wxString created for the - # parameter. - - # ascii - result = wx.testStringTypemap('hello') - self.assertTrue(type(result) == unicode) - self.assertTrue(result == unicode('hello')) - - # unicode should pass through unmodified - result = wx.testStringTypemap(uni) - self.assertTrue(result == uni) - - # utf-8 is converted - result = wx.testStringTypemap(utf) - self.assertTrue(result == uni) - - # can't auto-convert this - with self.assertRaises(UnicodeDecodeError): - result = wx.testStringTypemap(iso) - - # utf-16-be - val = "\x00\xe9\x00l\x00\xe9\x00p\x00h\x00a\x00n\x00t" - with self.assertRaises(UnicodeDecodeError): - result = wx.testStringTypemap(val) - result = wx.testStringTypemap( val.decode('utf-16-be')) - self.assertTrue(result == uni) - - # utf-32-be - val = "\x00\x00\x00\xe9\x00\x00\x00l\x00\x00\x00\xe9\x00\x00\x00p\x00\x00\x00h\x00\x00\x00a\x00\x00\x00n\x00\x00\x00t" - with self.assertRaises(UnicodeDecodeError): - result = wx.testStringTypemap(val) - result = wx.testStringTypemap(val.decode('utf-32-be')) - self.assertTrue(result == uni) - - # utf-8 with BOM - #val = "\xef\xbb\xbfHello" - #result = wx.testStringTypemap(val) - #self.assertTrue(result == u'\ufeffHello') - - else: def test_StringTypemapsPy3(self): utf = b'\xc3\xa9l\xc3\xa9phant' # utf-8 bytes uni = utf.decode('utf-8') # convert to unicode diff --git a/unittests/test_variant.py b/unittests/test_variant.py index d4f9563c..d7b2f51d 100644 --- a/unittests/test_variant.py +++ b/unittests/test_variant.py @@ -2,8 +2,6 @@ import unittest from unittests import wtc import wx -import six - #--------------------------------------------------------------------------- class variant_Tests(wtc.WidgetTestCase): @@ -11,7 +9,7 @@ class variant_Tests(wtc.WidgetTestCase): @unittest.skipIf(not hasattr(wx, 'testVariantTypemap'), '') def test_variant1(self): n = wx.testVariantTypemap(123) - self.assertTrue(isinstance(n, six.integer_types)) + self.assertTrue(isinstance(n, int)) self.assertEqual(n, 123) diff --git a/unittests/test_window.py b/unittests/test_window.py index b8132b8e..fa466969 100644 --- a/unittests/test_window.py +++ b/unittests/test_window.py @@ -1,7 +1,6 @@ import unittest from unittests import wtc import wx -import six #--------------------------------------------------------------------------- @@ -15,7 +14,7 @@ class WindowTests(wtc.WidgetTestCase): def test_windowHandle(self): w = wx.Window(self.frame, -1, (10,10), (50,50)) hdl = w.GetHandle() - self.assertTrue(isinstance(hdl, six.integer_types)) + self.assertTrue(isinstance(hdl, int)) def test_windowProperties(self): diff --git a/unittests/test_wxdatetime.py b/unittests/test_wxdatetime.py index 62e7d141..ef56c912 100644 --- a/unittests/test_wxdatetime.py +++ b/unittests/test_wxdatetime.py @@ -1,6 +1,5 @@ import unittest import wx -import six from unittests import wtc import datetime import time @@ -45,12 +44,8 @@ class datetime_Tests(wtc.WidgetTestCase): def test_datetimeGetAmPm(self): am, pm = wx.DateTime.GetAmPmStrings() - if six.PY3: - base = str - else: - base = unicode - self.assertTrue(isinstance(am, base) and am != "") - self.assertTrue(isinstance(pm, base) and pm != "") + self.assertTrue(isinstance(am, str) and am != "") + self.assertTrue(isinstance(pm, str) and pm != "") def test_datetimeProperties(self): diff --git a/unittests/wtc.py b/unittests/wtc.py index 2ecb3d18..7ce9cb75 100644 --- a/unittests/wtc.py +++ b/unittests/wtc.py @@ -1,7 +1,6 @@ import unittest import wx import sys, os -import six #--------------------------------------------------------------------------- @@ -84,12 +83,9 @@ class WidgetTestCase(unittest.TestCase): def myExecfile(self, filename, ns): - if not six.PY3: - execfile(filename, ns) - else: - with open(filename, 'r') as f: - source = f.read() - exec(source, ns) + with open(filename, 'r') as f: + source = f.read() + exec(source, ns) def execSample(self, name): @@ -109,10 +105,7 @@ class Namespace(object): #--------------------------------------------------------------------------- def mybytes(text): - if six.PY3: - return bytes(text, 'utf-8') - else: - return str(text) + return bytes(text, 'utf-8') #--------------------------------------------------------------------------- diff --git a/wx/lib/CDate.py b/wx/lib/CDate.py index d6d2068b..4a91dca2 100644 --- a/wx/lib/CDate.py +++ b/wx/lib/CDate.py @@ -15,7 +15,6 @@ # in a string format, then an error was raised. # """Date and calendar classes and date utitility methods.""" -from __future__ import division import time # I18N diff --git a/wx/lib/agw/artmanager.py b/wx/lib/agw/artmanager.py index fb8f0e93..797442e9 100644 --- a/wx/lib/agw/artmanager.py +++ b/wx/lib/agw/artmanager.py @@ -6,7 +6,7 @@ This module contains drawing routines and customizations for the AGW widgets import wx import random -from six import BytesIO +from io import BytesIO from .fmresources import * diff --git a/wx/lib/agw/aui/auibar.py b/wx/lib/agw/aui/auibar.py index 27eecde4..8a59d8c7 100644 --- a/wx/lib/agw/aui/auibar.py +++ b/wx/lib/agw/aui/auibar.py @@ -31,9 +31,6 @@ import wx from .aui_utilities import BitmapFromBits, StepColour, GetLabelSize from .aui_utilities import GetBaseColour, MakeDisabledBitmap - -import six - from .aui_constants import * @@ -68,7 +65,7 @@ class CommandToolBarEvent(wx.PyCommandEvent): :param integer `win_id`: the window identification number. """ - if type(command_type) in six.integer_types: + if type(command_type) in int: wx.PyCommandEvent.__init__(self, command_type, win_id) else: wx.PyCommandEvent.__init__(self, command_type.GetEventType(), command_type.GetId()) @@ -158,7 +155,7 @@ class AuiToolBarEvent(CommandToolBarEvent): CommandToolBarEvent.__init__(self, command_type, win_id) - if type(command_type) in six.integer_types: + if type(command_type) in int: self.notify = wx.NotifyEvent(command_type, win_id) else: self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId()) diff --git a/wx/lib/agw/aui/auibook.py b/wx/lib/agw/aui/auibook.py index c63e31ec..573cfd22 100644 --- a/wx/lib/agw/aui/auibook.py +++ b/wx/lib/agw/aui/auibook.py @@ -32,7 +32,6 @@ import wx import datetime from wx.lib.expando import ExpandoTextCtrl -import six from . import tabart as TA @@ -392,7 +391,7 @@ class CommandNotebookEvent(wx.PyCommandEvent): :param integer `win_id`: the window identification number. """ - if type(command_type) in six.integer_types: + if type(command_type) in int: wx.PyCommandEvent.__init__(self, command_type, win_id) else: wx.PyCommandEvent.__init__(self, command_type.GetEventType(), command_type.GetId()) @@ -525,7 +524,7 @@ class AuiNotebookEvent(CommandNotebookEvent): CommandNotebookEvent.__init__(self, command_type, win_id) - if type(command_type) in six.integer_types: + if type(command_type) in int: self.notify = wx.NotifyEvent(command_type, win_id) else: self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId()) @@ -1174,7 +1173,7 @@ class AuiTabContainer(object): :param `wndOrInt`: an instance of :class:`wx.Window` or an integer specifying a tab index. """ - if type(wndOrInt) in six.integer_types: + if type(wndOrInt) in int: if wndOrInt >= len(self._pages): return False @@ -4081,7 +4080,7 @@ class AuiNotebook(wx.Panel): if page >= self._tabs.GetPageCount(): return False - if not isinstance(image, six.integer_types): + if not isinstance(image, int): raise Exception("The image parameter must be an integer, you passed " \ "%s"%repr(image)) diff --git a/wx/lib/agw/aui/framemanager.py b/wx/lib/agw/aui/framemanager.py index 10cc6bb5..2f7bdae5 100644 --- a/wx/lib/agw/aui/framemanager.py +++ b/wx/lib/agw/aui/framemanager.py @@ -106,8 +106,6 @@ except ImportError: # clock is removed in py3.8 from time import clock as perf_counter import warnings -import six - from . import auibar from . import auibook @@ -993,7 +991,7 @@ class AuiPaneInfo(object): ret = self.MinSize1(arg1) elif isinstance(arg1, tuple): ret = self.MinSize1(wx.Size(*arg1)) - elif isinstance(arg1, six.integer_types) and arg2 is not None: + elif isinstance(arg1, int) and arg2 is not None: ret = self.MinSize2(arg1, arg2) else: raise Exception("Invalid argument passed to `MinSize`: arg1=%s, arg2=%s" % (repr(arg1), repr(arg2))) @@ -1034,7 +1032,7 @@ class AuiPaneInfo(object): ret = self.MaxSize1(arg1) elif isinstance(arg1, tuple): ret = self.MaxSize1(wx.Size(*arg1)) - elif isinstance(arg1, six.integer_types) and arg2 is not None: + elif isinstance(arg1, int) and arg2 is not None: ret = self.MaxSize2(arg1, arg2) else: raise Exception("Invalid argument passed to `MaxSize`: arg1=%s, arg2=%s" % (repr(arg1), repr(arg2))) @@ -1077,7 +1075,7 @@ class AuiPaneInfo(object): ret = self.BestSize1(arg1) elif isinstance(arg1, tuple): ret = self.BestSize1(wx.Size(*arg1)) - elif isinstance(arg1, six.integer_types) and arg2 is not None: + elif isinstance(arg1, int) and arg2 is not None: ret = self.BestSize2(arg1, arg2) else: raise Exception("Invalid argument passed to `BestSize`: arg1=%s, arg2=%s" % (repr(arg1), repr(arg2))) @@ -4128,7 +4126,7 @@ class AuiManager(wx.EvtHandler): :param `item`: either a pane name or a :class:`wx.Window`. """ - if isinstance(item, six.string_types): + if isinstance(item, str): return self.GetPaneByName(item) else: return self.GetPaneByWidget(item) @@ -6471,7 +6469,7 @@ class AuiManager(wx.EvtHandler): elif paneInfo.IsNotebookControl() and not paneInfo.window: paneInfo.window = self._notebooks[paneInfo.notebook_id] - for notebook_id, pnp in six.iteritems(pages_and_panes): + for notebook_id, pnp in pages_and_panes.items(): # sort the panes with dock_pos sorted_pnp = sorted(pnp, key=lambda pane: pane.dock_pos) notebook = self._notebooks[notebook_id] @@ -9928,7 +9926,7 @@ class AuiManager(wx.EvtHandler): if not restoreToolAlreadyInToolbar: tool = minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap, - _(six.u("Restore %s")) % paneInfo.caption, target=target) + _("Restore %s") % paneInfo.caption, target=target) tool.SetUserData((ID_RESTORE_FRAME, paneInfo.window)) minimize_toolbar.SetAuiManager(self) minimize_toolbar.Realize() diff --git a/wx/lib/agw/customtreectrl.py b/wx/lib/agw/customtreectrl.py index 40bd1fb4..c48926b2 100644 --- a/wx/lib/agw/customtreectrl.py +++ b/wx/lib/agw/customtreectrl.py @@ -349,8 +349,6 @@ License And Version Latest Revision: Helio Guilherme @ 09 Aug 2018, 21.35 GMT -Version 2.7 - """ # Version Info @@ -359,9 +357,6 @@ __version__ = "2.7" import wx from wx.lib.expando import ExpandoTextCtrl -# Python 2/3 compatibility helper -import six - # ---------------------------------------------------------------------------- # Constants # ---------------------------------------------------------------------------- diff --git a/wx/lib/agw/flatmenu.py b/wx/lib/agw/flatmenu.py index e8678491..9ff0e3ef 100644 --- a/wx/lib/agw/flatmenu.py +++ b/wx/lib/agw/flatmenu.py @@ -200,8 +200,6 @@ import math import wx.lib.colourutils as colourutils -import six - from .fmcustomizedlg import FMCustomizeDlg from .artmanager import ArtManager, DCSaver from .fmresources import * @@ -590,7 +588,7 @@ class FMRenderer(object): else: - stream = six.BytesIO(xpm) + stream = io.BytesIO(xpm) img = wx.Image(stream) return wx.Bitmap(img) @@ -2226,7 +2224,7 @@ class MenuEntryInfo(object): :param integer `cmd`: the menu accelerator identifier. """ - if isinstance(titleOrMenu, six.string_types): + if isinstance(titleOrMenu, str): self._title = titleOrMenu self._menu = menu @@ -3595,7 +3593,7 @@ class FlatMenuBar(wx.Panel): if self._showCustomize: if invT + invM > 0: self._moreMenu.AppendSeparator() - item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, _(six.u("Customize..."))) + item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, _("Customize...")) self._moreMenu.AppendItem(item) diff --git a/wx/lib/agw/flatnotebook.py b/wx/lib/agw/flatnotebook.py index 987a70a9..91043e6a 100644 --- a/wx/lib/agw/flatnotebook.py +++ b/wx/lib/agw/flatnotebook.py @@ -192,8 +192,6 @@ import math import weakref import pickle -import six - # Used on OSX to get access to carbon api constants if wx.Platform == '__WXMAC__': try: @@ -6550,7 +6548,7 @@ class PageContainer(wx.Panel): if page < len(self._pagesInfoVec): return self._pagesInfoVec[page].GetCaption() else: - return six.u('') + return '' def SetPageText(self, page, text): diff --git a/wx/lib/agw/floatspin.py b/wx/lib/agw/floatspin.py index cb6be099..57afe5e5 100644 --- a/wx/lib/agw/floatspin.py +++ b/wx/lib/agw/floatspin.py @@ -177,10 +177,7 @@ import wx import locale from math import ceil, floor -# Python 2/3 compatibility helper -import six -if six.PY3: - long = int +long = int # Set The Styles For The Underline wx.TextCtrl FS_READONLY = 1 @@ -1379,7 +1376,7 @@ class FixedPoint(object): self.n = n return - if isinstance(value, six.integer_types): + if isinstance(value, int): self.n = int(value) * _tento(p) return diff --git a/wx/lib/agw/fmcustomizedlg.py b/wx/lib/agw/fmcustomizedlg.py index e7b06307..4a1c407a 100644 --- a/wx/lib/agw/fmcustomizedlg.py +++ b/wx/lib/agw/fmcustomizedlg.py @@ -14,14 +14,9 @@ This module contains a custom dialog class used to personalize the appearance of a :class:`~wx.lib.agw.flatmenu.FlatMenu` on the fly, allowing also the user of your application to do the same. """ +from collections import UserDict import wx -import six - -if six.PY2: - from UserDict import UserDict -else: - from collections import UserDict from .artmanager import ArtManager from .fmresources import * diff --git a/wx/lib/agw/hypertreelist.py b/wx/lib/agw/hypertreelist.py index 19c9be6f..02ba644d 100644 --- a/wx/lib/agw/hypertreelist.py +++ b/wx/lib/agw/hypertreelist.py @@ -302,9 +302,6 @@ from wx.lib.agw.customtreectrl import DragImage, TreeEvent, GenericTreeItem, Cho from wx.lib.agw.customtreectrl import TreeEditTimer as TreeListEditTimer from wx.lib.agw.customtreectrl import EVT_TREE_ITEM_CHECKING, EVT_TREE_ITEM_CHECKED, EVT_TREE_ITEM_HYPERLINK -# Python 2/3 compatibility helper -import six - if sys.version_info >= (3, 11): from typing import Self else: @@ -458,7 +455,7 @@ class TreeListColumnInfo(object): :param `edit`: ``True`` to set the column as editable, ``False`` otherwise. """ - if isinstance(input, six.string_types): + if isinstance(input, str): self._text = input self._width = width self._flag = flag @@ -3667,7 +3664,7 @@ class TreeListMainWindow(CustomTreeCtrl): if self._curColumn == -1: self._curColumn = 0 - self.SetItemText(self._editItem, six.text_type(value), self._curColumn) + self.SetItemText(self._editItem, str(value), self._curColumn) def OnCancelEdit(self): diff --git a/wx/lib/agw/persist/persist_constants.py b/wx/lib/agw/persist/persist_constants.py index 1f454fa6..a5f26652 100644 --- a/wx/lib/agw/persist/persist_constants.py +++ b/wx/lib/agw/persist/persist_constants.py @@ -12,7 +12,6 @@ This module contains all the constants used by the persistent objects. import wx import wx.dataview as dv -import six # ----------------------------------------------------------------------------------- # # PersistenceManager styles @@ -33,14 +32,14 @@ BAD_DEFAULT_NAMES = ["widget", "wxSpinButton", "auiFloating", "AuiTabCtrl", "mas for name in dir(wx): if "NameStr" in name: val = getattr(wx, name) - if six.PY3 and isinstance(val, bytes): + if isinstance(val, bytes): val = val.decode('utf-8') BAD_DEFAULT_NAMES.append(val) for name in dir(dv): if "NameStr" in name: val = getattr(dv, name) - if six.PY3 and isinstance(val, bytes): + if isinstance(val, bytes): val = val.decode('utf-8') BAD_DEFAULT_NAMES.append(val) diff --git a/wx/lib/agw/persist/persistencemanager.py b/wx/lib/agw/persist/persistencemanager.py index a787d4eb..d448fffb 100644 --- a/wx/lib/agw/persist/persistencemanager.py +++ b/wx/lib/agw/persist/persistencemanager.py @@ -35,7 +35,6 @@ import datetime import wx import wx.adv -import six from .persist_handlers import FindHandler, HasCtrlHandler @@ -44,7 +43,7 @@ from .persist_constants import PM_DEFAULT_STYLE, PM_PERSIST_CONTROL_VALUE # ----------------------------------------------------------------------------------- # -class PersistentObject(object): +class PersistentObject: """ :class:`PersistentObject`: ABC for anything persistent. @@ -785,10 +784,10 @@ class PersistenceManager(object): kind = repr(value.__class__).split("'")[1] if self._customConfigHandler is not None: - result = self._customConfigHandler.SaveValue(self.GetKey(obj, keyName), repr((kind, six.text_type(value)))) + result = self._customConfigHandler.SaveValue(self.GetKey(obj, keyName), repr((kind, str(value)))) else: config = self.GetPersistenceFile() - result = config.Write(self.GetKey(obj, keyName), repr((kind, six.text_type(value)))) + result = config.Write(self.GetKey(obj, keyName), repr((kind, str(value)))) config.Flush() return result diff --git a/wx/lib/agw/ribbon/bar.py b/wx/lib/agw/ribbon/bar.py index c3ea1a35..09004dfd 100644 --- a/wx/lib/agw/ribbon/bar.py +++ b/wx/lib/agw/ribbon/bar.py @@ -98,8 +98,6 @@ See Also import wx from functools import cmp_to_key -import six - from .control import RibbonControl from .art_internal import RibbonPageTabInfo @@ -607,7 +605,7 @@ class RibbonBar(RibbonControl): def SetActivePage(self, page): """ See comments on :meth:`~RibbonBar.SetActivePageByIndex` and :meth:`~RibbonBar.SetActivePageByPage`. """ - if isinstance(page, six.integer_types): + if isinstance(page, int): return self.SetActivePageByIndex(page) return self.SetActivePageByPage(page) diff --git a/wx/lib/agw/ribbon/buttonbar.py b/wx/lib/agw/ribbon/buttonbar.py index 577da693..8df44b01 100644 --- a/wx/lib/agw/ribbon/buttonbar.py +++ b/wx/lib/agw/ribbon/buttonbar.py @@ -46,8 +46,6 @@ Event Name Description import wx -import six - from .control import RibbonControl from .art import * @@ -345,7 +343,7 @@ class RibbonButtonBar(RibbonControl): if not bitmap.IsOk() and not bitmap_small.IsOk(): raise Exception("Invalid main bitmap") - if not isinstance(help_string, six.string_types): + if not isinstance(help_string, str): raise Exception("Invalid help string parameter") if not self._buttons: diff --git a/wx/lib/agw/rulerctrl.py b/wx/lib/agw/rulerctrl.py index b13ae51a..c2aeca8f 100644 --- a/wx/lib/agw/rulerctrl.py +++ b/wx/lib/agw/rulerctrl.py @@ -153,6 +153,7 @@ Version 0.4 """ +import io import wx import math import zlib @@ -166,9 +167,6 @@ try: except: pass -# Python 2/3 compatibility helper -import six - # Built-in formats IntFormat = 1 """ Integer format. """ @@ -225,7 +223,7 @@ def GetIndicatorBitmap(): def GetIndicatorImage(): """ Returns the image indicator as a :class:`wx.Image`. """ - stream = six.BytesIO(GetIndicatorData()) + stream = io.BytesIO(GetIndicatorData()) return wx.Image(stream) diff --git a/wx/lib/agw/scrolledthumbnail.py b/wx/lib/agw/scrolledthumbnail.py index 437e6c55..22155816 100644 --- a/wx/lib/agw/scrolledthumbnail.py +++ b/wx/lib/agw/scrolledthumbnail.py @@ -173,18 +173,15 @@ Version 1.0 # Beginning Of ThumbnailCtrl wxPython Code #---------------------------------------------------------------------- +import io import os import wx -import six import zlib from math import radians from wx.lib.embeddedimage import PyEmbeddedImage -if six.PY3: - import _thread as thread -else: - import thread +import _thread as thread #---------------------------------------------------------------------- # Get Default Icon/Data @@ -308,9 +305,9 @@ b'x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xac \xcc\xc1\ def getShadow(): """ Creates a shadow behind every thumbnail. """ - sh_tr = wx.Image(six.BytesIO(getDataTR())).ConvertToBitmap() - sh_bl = wx.Image(six.BytesIO(getDataBL())).ConvertToBitmap() - sh_sh = wx.Image(six.BytesIO(getDataSH())).Rescale(500, 500, wx.IMAGE_QUALITY_HIGH) + sh_tr = wx.Image(io.BytesIO(getDataTR())).ConvertToBitmap() + sh_bl = wx.Image(io.BytesIO(getDataBL())).ConvertToBitmap() + sh_sh = wx.Image(io.BytesIO(getDataSH())).Rescale(500, 500, wx.IMAGE_QUALITY_HIGH) return (sh_tr, sh_bl, sh_sh.ConvertToBitmap()) diff --git a/wx/lib/agw/ultimatelistctrl.py b/wx/lib/agw/ultimatelistctrl.py index e12da76f..1c12dd8f 100644 --- a/wx/lib/agw/ultimatelistctrl.py +++ b/wx/lib/agw/ultimatelistctrl.py @@ -236,11 +236,10 @@ Version 0.8 import wx import math import bisect +import io import zlib from functools import cmp_to_key -import six - from wx.lib.expando import ExpandoTextCtrl # Version Info @@ -550,7 +549,7 @@ IL_FIXED_SIZE = 0 IL_VARIABLE_SIZE = 1 # Python integers, to make long types to work with CreateListItem -INTEGER_TYPES = six.integer_types +INTEGER_TYPES = int # ---------------------------------------------------------------------------- @@ -652,7 +651,7 @@ def GetdragcursorBitmap(): def GetdragcursorImage(): """ Returns the drag and drop cursor image as a :class:`wx.Image`. """ - stream = six.BytesIO(GetdragcursorData()) + stream = io.BytesIO(GetdragcursorData()) return wx.Image(stream) @@ -13124,9 +13123,9 @@ class UltimateListCtrl(wx.Control): if entry: pos = self.GetItemCount() - self.InsertStringItem(pos, six.u(entry[0])) + self.InsertStringItem(pos, str(entry[0])) for i in range(1, len(entry)): - self.SetStringItem(pos, i, six.u(entry[i])) + self.SetStringItem(pos, i, str(entry[i])) return pos diff --git a/wx/lib/agw/xlsgrid.py b/wx/lib/agw/xlsgrid.py index c8676c66..7583a2a3 100644 --- a/wx/lib/agw/xlsgrid.py +++ b/wx/lib/agw/xlsgrid.py @@ -250,8 +250,6 @@ import string import wx.grid as gridlib -import six - from wx.lib.embeddedimage import PyEmbeddedImage from wx.lib.wordwrap import wordwrap @@ -439,8 +437,8 @@ def SplitThousands(s, tSep=',', dSep='.'): """ - if not isinstance(s, six.string_types): - s = six.u(s) + if not isinstance(s, str): + s = str(s) cnt = 0 numChars = dSep + '0123456789' @@ -837,7 +835,7 @@ class XLSText(object): value = representation%value except ValueError: # Fall back to string - value = six.u(value) + value = str(value) if "#," in number_format: value = SplitThousands(value) diff --git a/wx/lib/colourchooser/__init__.py b/wx/lib/colourchooser/__init__.py index b149067f..31ddf517 100644 --- a/wx/lib/colourchooser/__init__.py +++ b/wx/lib/colourchooser/__init__.py @@ -12,8 +12,6 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. """ -from __future__ import absolute_import - # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatibility update. diff --git a/wx/lib/colourchooser/pycolourchooser.py b/wx/lib/colourchooser/pycolourchooser.py index 12437648..6c3beae8 100644 --- a/wx/lib/colourchooser/pycolourchooser.py +++ b/wx/lib/colourchooser/pycolourchooser.py @@ -12,8 +12,6 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. """ -from __future__ import absolute_import - # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatibility update. diff --git a/wx/lib/colourchooser/pycolourslider.py b/wx/lib/colourchooser/pycolourslider.py index f7f043a0..b88cd527 100644 --- a/wx/lib/colourchooser/pycolourslider.py +++ b/wx/lib/colourchooser/pycolourslider.py @@ -16,8 +16,6 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. """ -from __future__ import absolute_import - # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatibility update. diff --git a/wx/lib/colourchooser/pypalette.py b/wx/lib/colourchooser/pypalette.py index 71b9fc2d..cb81d2b5 100644 --- a/wx/lib/colourchooser/pypalette.py +++ b/wx/lib/colourchooser/pypalette.py @@ -16,8 +16,6 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. """ -from __future__ import absolute_import - # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatibility update. diff --git a/wx/lib/embeddedimage.py b/wx/lib/embeddedimage.py index 116de595..6ba4674e 100644 --- a/wx/lib/embeddedimage.py +++ b/wx/lib/embeddedimage.py @@ -13,9 +13,9 @@ #---------------------------------------------------------------------- import base64 +from io import BytesIO import wx -from six import BytesIO try: b64decode = base64.b64decode @@ -23,7 +23,7 @@ except AttributeError: b64decode = base64.decodestring -class PyEmbeddedImage(object): +class PyEmbeddedImage: """ PyEmbeddedImage is primarily intended to be used by code generated by img2py as a means of embedding image data in a python module so diff --git a/wx/lib/fancytext.py b/wx/lib/fancytext.py index ee78f2a6..862cc133 100644 --- a/wx/lib/fancytext.py +++ b/wx/lib/fancytext.py @@ -58,7 +58,6 @@ import math import sys import wx -import six import xml.parsers.expat @@ -255,8 +254,6 @@ class Renderer: def renderCharacterData(self, data, x, y): raise NotImplementedError() -from six import PY3 - def _addGreek(): alpha = 0xE1 Alpha = 0xC1 @@ -265,10 +262,7 @@ def _addGreek(): for i, name in enumerate(_greek_letters): def start(self, attrs, code=chr(alpha+i)): self.start_font({"encoding" : _greekEncoding}) - if not PY3: - self.characterData(code.decode('iso8859-7')) - else: - self.characterData(code) + self.characterData(code) self.end_font() setattr(Renderer, "start_%s" % name, start) setattr(Renderer, "end_%s" % name, end) @@ -276,10 +270,7 @@ def _addGreek(): continue # There is no capital for altsigma def start(self, attrs, code=chr(Alpha+i)): self.start_font({"encoding" : _greekEncoding}) - if not PY3: - self.characterData(code.decode('iso8859-7')) - else: - self.characterData(code) + self.characterData(code) self.end_font() setattr(Renderer, "start_%s" % name.capitalize(), start) setattr(Renderer, "end_%s" % name.capitalize(), end) @@ -366,8 +357,6 @@ def RenderToRenderer(str, renderer, enclose=True): if enclose: str = '%s' % str p = xml.parsers.expat.ParserCreate() - if six.PY2: - p.returns_unicode = 0 p.StartElementHandler = renderer.startElement p.EndElementHandler = renderer.endElement p.CharacterDataHandler = renderer.characterData diff --git a/wx/lib/floatcanvas/FCObjects.py b/wx/lib/floatcanvas/FCObjects.py index bf307bdc..1ddc62b1 100644 --- a/wx/lib/floatcanvas/FCObjects.py +++ b/wx/lib/floatcanvas/FCObjects.py @@ -17,7 +17,6 @@ This is where FloatCanvas defines its drawings objects. import sys import wx -import six import numpy as N @@ -228,14 +227,8 @@ class DrawObject: if not self._Canvas.HitColorGenerator: # first call to prevent the background color from being used. self._Canvas.HitColorGenerator = _colorGenerator() - if six.PY3: - next(self._Canvas.HitColorGenerator) - else: - self._Canvas.HitColorGenerator.next() - if six.PY3: - self.HitColor = next(self._Canvas.HitColorGenerator) - else: - self.HitColor = self._Canvas.HitColorGenerator.next() + next(self._Canvas.HitColorGenerator) + self.HitColor = next(self._Canvas.HitColorGenerator) self.SetHitPen(self.HitColor,self.HitLineWidth) self.SetHitBrush(self.HitColor) # put the object in the hit dict, indexed by it's color @@ -2890,15 +2883,9 @@ class Group(DrawObject): if not self._Canvas.HitColorGenerator: self._Canvas.HitColorGenerator = _colorGenerator() # first call to prevent the background color from being used. - if six.PY2: - self._Canvas.HitColorGenerator.next() - else: - next(self._Canvas.HitColorGenerator) + next(self._Canvas.HitColorGenerator) # Set all contained objects to the same Hit color: - if six.PY2: - self.HitColor = self._Canvas.HitColorGenerator.next() - else: - self.HitColor = next(self._Canvas.HitColorGenerator) + self.HitColor = next(self._Canvas.HitColorGenerator) self._ChangeChildrenHitColor(self.ObjectList) # put the object in the hit dict, indexed by it's color if not self._Canvas.HitDict: diff --git a/wx/lib/floatcanvas/FloatCanvas.py b/wx/lib/floatcanvas/FloatCanvas.py index ebdd689f..9e77d769 100644 --- a/wx/lib/floatcanvas/FloatCanvas.py +++ b/wx/lib/floatcanvas/FloatCanvas.py @@ -42,8 +42,6 @@ Many samples are available in the `wxPhoenix/samples/floatcanvas` folder. """ -from __future__ import division - import sys mac = sys.platform.startswith("darwin") @@ -53,7 +51,6 @@ try: except ImportError: from time import clock import wx -import six from .FCObjects import * diff --git a/wx/lib/floatcanvas/Resources.py b/wx/lib/floatcanvas/Resources.py index 7235c456..0065e079 100644 --- a/wx/lib/floatcanvas/Resources.py +++ b/wx/lib/floatcanvas/Resources.py @@ -4,7 +4,7 @@ from wx import Image as ImageFromStream from wx import Bitmap as BitmapFromImage -from six import BytesIO +from io import BytesIO import zlib diff --git a/wx/lib/floatcanvas/ScreenShot.py b/wx/lib/floatcanvas/ScreenShot.py index e26d856a..3ac33b90 100644 --- a/wx/lib/floatcanvas/ScreenShot.py +++ b/wx/lib/floatcanvas/ScreenShot.py @@ -4,7 +4,7 @@ from wx import Image as ImageFromStream from wx import BitmapFromImage -from six import BytesIO +from io import BytesIO import zlib diff --git a/wx/lib/graphics.py b/wx/lib/graphics.py index c02783fd..71cbf5a0 100644 --- a/wx/lib/graphics.py +++ b/wx/lib/graphics.py @@ -39,7 +39,6 @@ the ``wx.GraphicsContext`` classes a little better than Cairo's. import sys import math -import six import wx import wx.lib.wxcairo as wxcairo @@ -1890,7 +1889,7 @@ def _makeColour(colour): Helper which makes a wx.Colour from any of the allowed typemaps (string, tuple, etc.) """ - if isinstance(colour, (six.string_types, tuple)): + if isinstance(colour, (str, tuple)): return wx.NamedColour(colour) else: return colour diff --git a/wx/lib/inspection.py b/wx/lib/inspection.py index 4d2d1c7d..53b77dda 100644 --- a/wx/lib/inspection.py +++ b/wx/lib/inspection.py @@ -28,7 +28,6 @@ import wx.py import wx.stc #import wx.aui as aui import wx.lib.agw.aui as aui -import six import wx.lib.utils as utils import sys import inspect @@ -635,7 +634,7 @@ class InspectionInfoPanel(wx.stc.StyledTextCtrl): def Fmt(self, name, value): - if isinstance(value, six.string_types): + if isinstance(value, str): return " %s = '%s'" % (name, value) else: return " %s = %s" % (name, value) diff --git a/wx/lib/intctrl.py b/wx/lib/intctrl.py index c4ca9ea9..f1740cc1 100644 --- a/wx/lib/intctrl.py +++ b/wx/lib/intctrl.py @@ -47,11 +47,7 @@ import six MAXSIZE = six.MAXSIZE # (constants should be in upper case) MINSIZE = -six.MAXSIZE-1 - -if six.PY2: - LONGTYPE = long -else: - LONGTYPE = int +LONGTYPE = int #---------------------------------------------------------------------------- @@ -469,10 +465,7 @@ class IntCtrl(wx.TextCtrl): self.__default_color = wx.BLACK self.__oob_color = wx.RED self.__allow_none = 0 - if six.PY2: - self.__allow_long = 0 - else: - self.__allow_long = 1 + self.__allow_long = 1 self.__oldvalue = None if validator == wx.DefaultValidator: @@ -491,10 +484,7 @@ class IntCtrl(wx.TextCtrl): self.SetLimited(limited) self.SetColors(default_color, oob_color) self.SetNoneAllowed(allow_none) - if six.PY2: - self.SetLongAllowed(allow_long) - else: - self.SetLongAllowed(1) + self.SetLongAllowed(1) self.ChangeValue(value) def OnText( self, event ): @@ -708,7 +698,7 @@ class IntCtrl(wx.TextCtrl): value = self.GetValue() if( not (value is None and self.IsNoneAllowed()) - and type(value) not in six.integer_types ): + and type(value) not in int ): raise ValueError ( 'IntCtrl requires integer values, passed %s'% repr(value) ) @@ -820,7 +810,7 @@ class IntCtrl(wx.TextCtrl): elif type(value) == LONGTYPE and not self.IsLongAllowed(): raise ValueError ( 'IntCtrl requires integer value, passed long' ) - elif type(value) not in six.integer_types: + elif type(value) not in int: raise ValueError ( 'IntCtrl requires integer value, passed %s'% repr(value) ) diff --git a/wx/lib/masked/combobox.py b/wx/lib/masked/combobox.py index f9afb1f7..484368c7 100644 --- a/wx/lib/masked/combobox.py +++ b/wx/lib/masked/combobox.py @@ -478,7 +478,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ): penalty. """ if self._mask: - if not isinstance(choice, six.string_types): + if not isinstance(choice, str): raise TypeError('%s: choices must be a sequence of strings' % str(self._index)) elif not self.IsValid(choice): raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice)) @@ -731,7 +731,7 @@ class BaseMaskedComboBox( wx.ComboBox, MaskedEditMixin ): # work around bug in wx 2.5 wx.CallAfter(self.SetInsertionPoint, 0) wx.CallAfter(self.SetInsertionPoint, end) - elif isinstance(match_index, six.string_types): + elif isinstance(match_index, str): ## dbg('CallAfter SetValue') # Preserve the textbox contents # See commentary in _OnReturn docstring. diff --git a/wx/lib/masked/ipaddrctrl.py b/wx/lib/masked/ipaddrctrl.py index 0ea398e0..a20f8da9 100644 --- a/wx/lib/masked/ipaddrctrl.py +++ b/wx/lib/masked/ipaddrctrl.py @@ -23,7 +23,6 @@ user hits '.' when typing. """ import wx -import six from wx.lib.masked import BaseMaskedTextCtrl # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would @@ -188,7 +187,7 @@ class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ): """ ## dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1) - if not isinstance(value, six.string_types): + if not isinstance(value, str): ## dbg(indent=0) raise ValueError('%s must be a string' % str(value)) diff --git a/wx/lib/masked/maskededit.py b/wx/lib/masked/maskededit.py index 23391c28..87335d42 100644 --- a/wx/lib/masked/maskededit.py +++ b/wx/lib/masked/maskededit.py @@ -813,7 +813,6 @@ import string import sys import wx -import six # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would # be a good place to implement the 2.3 logger class @@ -1490,7 +1489,7 @@ class Field: raise TypeError('%s: choices must be a sequence of strings' % str(self._index)) elif len( self._choices) > 0: for choice in self._choices: - if not isinstance(choice, six.string_types): + if not isinstance(choice, str): ## dbg(indent=0, suspend=0) raise TypeError('%s: choices must be a sequence of strings' % str(self._index)) @@ -1954,7 +1953,7 @@ class MaskedEditMixin: for key in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour', 'foregroundColour', 'signedForegroundColour'): if key in ctrl_kwargs: - if isinstance(ctrl_kwargs[key], six.string_types): + if isinstance(ctrl_kwargs[key], str): c = wx.Colour(ctrl_kwargs[key]) if c.Get() == (-1, -1, -1): raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key)) @@ -3062,23 +3061,15 @@ class MaskedEditMixin: if key < 256: char = chr(key) # (must work if we got this far) - if not six.PY3: - char = char.decode(self._defaultEncoding) else: char = unichr(event.GetUnicodeKey()) ## dbg('unicode char:', char) - excludes = six.text_type() - if not isinstance(field._excludeChars, six.text_type): - if six.PY3: - excludes += field._excludeChars - else: - excludes += field._excludeChars.decode(self._defaultEncoding) - if not isinstance(self._ctrl_constraints, six.text_type): - if six.PY3: - excludes += field._excludeChars - else: - excludes += self._ctrl_constraints._excludeChars.decode(self._defaultEncoding) + excludes = str() + if not isinstance(field._excludeChars, str): + excludes += field._excludeChars + if not isinstance(self._ctrl_constraints, str): + excludes += field._excludeChars else: excludes += self._ctrl_constraints._excludeChars @@ -4634,11 +4625,6 @@ class MaskedEditMixin: maskChar = self.maskdict[pos] okchars = self.maskchardict[maskChar] ## entry, get mask approved characters - # convert okchars to unicode if required; will force subsequent appendings to - # result in unicode strings - if not six.PY3 and not isinstance(okchars, six.text_type): - okchars = okchars.decode(self._defaultEncoding) - field = self._FindField(pos) if okchars and field._okSpaces: ## Allow spaces? okchars += " " @@ -5225,12 +5211,6 @@ class MaskedEditMixin: left = text[0:pos] right = text[pos+1:] - if not isinstance(char, six.text_type): - # convert the keyboard constant to a unicode value, to - # ensure it can be concatenated into the control value: - if not six.PY3: - char = char.decode(self._defaultEncoding) - newtext = left + char + right #### dbg('left: "%s"' % left) #### dbg('right: "%s"' % right) @@ -5764,8 +5744,6 @@ class MaskedEditMixin: else: item = 'selection' ## dbg('maxlength:', maxlength) - if not six.PY3 and not isinstance(paste_text, six.text_type): - paste_text = paste_text.decode(self._defaultEncoding) length_considered = len(paste_text) if length_considered > maxlength: @@ -5871,9 +5849,6 @@ class MaskedEditMixin: if paste_text is not None: - if not six.PY3 and not isinstance(paste_text, six.text_type): - paste_text = paste_text.decode(self._defaultEncoding) - ## dbg('paste text: "%s"' % paste_text) # (conversion will raise ValueError if paste isn't legal) sel_start, sel_to = self._GetSelection() diff --git a/wx/lib/masked/numctrl.py b/wx/lib/masked/numctrl.py index ac659c26..d0177d19 100644 --- a/wx/lib/masked/numctrl.py +++ b/wx/lib/masked/numctrl.py @@ -401,7 +401,6 @@ GetAutoSize() import copy import wx -import six from sys import maxsize MAXINT = maxsize # (constants should be in upper case) @@ -1641,7 +1640,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin): ## dbg(indent=0) return self._template - elif isinstance(value, six.string_types): + elif isinstance(value, str): value = self._GetNumValue(value) ## dbg('cleansed num value: "%s"' % value) if value == "": diff --git a/wx/lib/masked/timectrl.py b/wx/lib/masked/timectrl.py index 6ca738d3..32c1d619 100644 --- a/wx/lib/masked/timectrl.py +++ b/wx/lib/masked/timectrl.py @@ -281,7 +281,6 @@ IsLimited() import copy import wx -import six from wx.tools.dbg import Logger from wx.lib.masked import Field, BaseMaskedTextCtrl @@ -762,8 +761,8 @@ class TimeCtrl(BaseMaskedTextCtrl): ## dbg('value = "%s"' % value) valid = True # assume true - if isinstance(value, six.string_types): - value = six.text_type(value) # convert to regular string + if isinstance(value, str): + value = str(value) # convert to regular string # Construct constant wxDateTime, then try to parse the string: wxdt = wx.DateTime.FromDMY(1, 0, 1970) @@ -1385,7 +1384,7 @@ class TimeCtrl(BaseMaskedTextCtrl): if self.IsLimited() and not self.IsInBounds(value): ## dbg(indent=0) raise ValueError ( - 'value %s is not within the bounds of the control' % six.text_type(value) ) + 'value %s is not within the bounds of the control' % str(value) ) ## dbg(indent=0) return value diff --git a/wx/lib/mixins/listctrl.py b/wx/lib/mixins/listctrl.py index fe91d713..2d55ee85 100644 --- a/wx/lib/mixins/listctrl.py +++ b/wx/lib/mixins/listctrl.py @@ -33,12 +33,9 @@ import locale import wx -import six -if six.PY3: - # python 3 lacks cmp: - def cmp(a, b): - return (a > b) - (a < b) +def cmp(a, b): + return (a > b) - (a < b) #---------------------------------------------------------------------------- @@ -161,10 +158,10 @@ class ColumnSorterMixin: item2 = self.itemDataMap[key2][col] #--- Internationalization of string sorting with locale module - if isinstance(item1, six.text_type) and isinstance(item2, six.text_type): + if isinstance(item1, str) and isinstance(item2, str): # both are unicode (py2) or str (py3) cmpVal = locale.strcoll(item1, item2) - elif isinstance(item1, six.binary_type) or isinstance(item2, six.binary_type): + elif isinstance(item1, bytes) or isinstance(item2, bytes): # at least one is a str (py2) or byte (py3) cmpVal = locale.strcoll(str(item1), str(item2)) else: diff --git a/wx/lib/multisash.py b/wx/lib/multisash.py index 487c8aab..a55c7684 100644 --- a/wx/lib/multisash.py +++ b/wx/lib/multisash.py @@ -21,7 +21,6 @@ import wx -import six MV_HOR = 0 MV_VER = not MV_HOR @@ -63,7 +62,7 @@ class MultiSash(wx.Window): def SetSaveData(self,data): mod = data['_defChild_mod'] dChild = mod + '.' + data['_defChild_class'] - six.exec_('import %s' % mod) + exec('import %s' % mod) self._defChild = eval(dChild) old = self.child self.child = MultiSplit(self,self,wx.Point(0,0),self.GetSize()) @@ -327,7 +326,7 @@ class MultiViewLeaf(wx.Window): def SetSaveData(self,data): mod = data['detailClass_mod'] dChild = mod + '.' + data['detailClass_class'] - six.exec_('import %s' % mod) + exec('import %s' % mod) detClass = eval(dChild) self.SetSize(data['x'],data['y'],data['w'],data['h']) old = self.detail diff --git a/wx/lib/pdfviewer/viewer.py b/wx/lib/pdfviewer/viewer.py index 84745ec7..86ba7506 100644 --- a/wx/lib/pdfviewer/viewer.py +++ b/wx/lib/pdfviewer/viewer.py @@ -27,7 +27,7 @@ import bisect import itertools import copy import shutil -from six import BytesIO, string_types +from io import BytesIO import wx @@ -199,7 +199,7 @@ class pdfViewer(wx.ScrolledWindow): return BytesIO(stream) self.pdfpathname = '' - if isinstance(pdf_file, string_types): + if isinstance(pdf_file, str): # a filename/path string, save its name self.pdfpathname = pdf_file # remove comment from next line to test using a file-like object @@ -507,7 +507,7 @@ class mupdfProcessor(object): Could also be a string representing a path to a PDF file. """ self.parent = parent - if isinstance(pdf_file, string_types): + if isinstance(pdf_file, str): # a filename/path string, pass the name to pymupdf.open pathname = pdf_file self.pdfdoc = pymupdf.open(pathname) diff --git a/wx/lib/printout.py b/wx/lib/printout.py index abc42c60..4c68be68 100644 --- a/wx/lib/printout.py +++ b/wx/lib/printout.py @@ -27,9 +27,7 @@ import copy import types import wx -import six - -class PrintBase(object): +class PrintBase: def SetPrintFont(self, font): # set the DC font parameters fattr = font["Attr"] if fattr[0] == 1: @@ -273,7 +271,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase): self.column.append(pos_x) #module logic expects two dimensional data -- fix input if needed - if isinstance(self.data, six.string_types): + if isinstance(self.data, str): self.data = [[copy.copy(self.data)]] # a string becomes a single cell try: rows = len(self.data) @@ -282,7 +280,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase): rows = 1 first_value = self.data[0] - if isinstance(first_value, six.string_types): # a sequence of strings + if isinstance(first_value, str): # a sequence of strings if self.label == [] and self.set_column == []: data = [] for x in self.data: #becomes one column @@ -562,7 +560,7 @@ class PrintTableDraw(wx.ScrolledWindow, PrintBase): self.col = 0 max_y = 0 for vtxt in row_val: - if not isinstance(vtxt, six.string_types): + if not isinstance(vtxt, str): vtxt = str(vtxt) self.region = self.column[self.col+1] - self.column[self.col] self.indent = self.column[self.col] diff --git a/wx/lib/pubsub/core/callables.py b/wx/lib/pubsub/core/callables.py index 7e798c54..c6bb3fdd 100644 --- a/wx/lib/pubsub/core/callables.py +++ b/wx/lib/pubsub/core/callables.py @@ -11,13 +11,14 @@ CallArgsInfo regarding its autoTopicArgName data member. :license: BSD, see LICENSE_BSD_Simple.txt for details. """ +import sys from inspect import ismethod, isfunction, signature, Parameter -from .. import py2and3 - AUTO_TOPIC = '## your listener wants topic name ## (string unlikely to be used by caller)' +def getexcobj(): + return sys.exc_info()[1] def getModule(obj): """Get the module in which an object was defined. Returns '__main__' @@ -189,8 +190,7 @@ def getArgs(callable_): try: func, firstArgIdx = getRawFunction(callable_) except ValueError: - from .. import py2and3 - exc = py2and3.getexcobj() + exc = getexcobj() raise ListenerMismatchError(str(exc), callable_) return CallArgsInfo(func, firstArgIdx) diff --git a/wx/lib/pubsub/core/imp2.py b/wx/lib/pubsub/core/imp2.py index c4641e33..933c7b34 100644 --- a/wx/lib/pubsub/core/imp2.py +++ b/wx/lib/pubsub/core/imp2.py @@ -7,14 +7,13 @@ closely. """ import sys -from .. import py2and3 def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) - for x in py2and3.xrange(level, 1, -1): + for x in range(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: diff --git a/wx/lib/pubsub/core/kwargs/publisher.py b/wx/lib/pubsub/core/kwargs/publisher.py index 37c28d8c..bda42fc5 100644 --- a/wx/lib/pubsub/core/kwargs/publisher.py +++ b/wx/lib/pubsub/core/kwargs/publisher.py @@ -6,7 +6,7 @@ from .publisherbase import PublisherBase from .datamsg import Message -from .. import (policies, py2and3) +from .. import (policies) @@ -42,7 +42,7 @@ class PublisherArg1Stage2(Publisher): def __init__(self, kwargs, commonArgName): extra = kwargs.copy() del extra[commonArgName] - msg = 'Sender has too many kwargs (%s)' % ( py2and3.keys(extra),) + msg = 'Sender has too many kwargs (%s)' % ( extra.keys(),) RuntimeError.__init__(self, msg) class SenderWrongKwargName(RuntimeError): @@ -60,7 +60,7 @@ class PublisherArg1Stage2(Publisher): if len(kwarg) > 1: raise self.SenderTooManyKwargs(kwarg, commonArgName) elif len(kwarg) == 1 and commonArgName not in kwarg: - raise self.SenderWrongKwargName( py2and3.keys(kwarg)[0], commonArgName) + raise self.SenderWrongKwargName( kwarg.keys()[0], commonArgName) data = kwarg.get(commonArgName, None) kwargs = { commonArgName: self.Msg( _topicName, data) } diff --git a/wx/lib/pubsub/core/kwargs/topicargspecimpl.py b/wx/lib/pubsub/core/kwargs/topicargspecimpl.py index 73120d5c..ea9817f1 100644 --- a/wx/lib/pubsub/core/kwargs/topicargspecimpl.py +++ b/wx/lib/pubsub/core/kwargs/topicargspecimpl.py @@ -9,7 +9,6 @@ import weakref from .topicutils import (stringize, WeakNone) from .validatedefnargs import verifySubset -from .. import py2and3 ### Exceptions raised during check() from sendMessage() @@ -101,7 +100,7 @@ class ArgsInfo: """docs is a mapping from arg names to their documentation""" if not self.isComplete(): raise - for arg, doc in py2and3.iteritems(docs): + for arg, doc in docs.items(): self.allDocs[arg] = doc def check(self, msgKwargs): @@ -115,14 +114,14 @@ class ArgsInfo: hasReqd = (needReqd <= all) if not hasReqd: raise SenderMissingReqdMsgDataError( - self.topicNameTuple, py2and3.keys(msgKwargs), needReqd - all) + self.topicNameTuple, msgKwargs.keys(), needReqd - all) # check that all other args are among the optional spec optional = all - needReqd ok = (optional <= set(self.allOptional)) if not ok: raise SenderUnknownMsgDataError( self.topicNameTuple, - py2and3.keys(msgKwargs), optional - set(self.allOptional) ) + msgKwargs.keys(), optional - set(self.allOptional) ) def filterArgs(self, msgKwargs): """Returns a dict which contains only those items of msgKwargs diff --git a/wx/lib/pubsub/core/publisherbase.py b/wx/lib/pubsub/core/publisherbase.py index b48e3989..129f9388 100644 --- a/wx/lib/pubsub/core/publisherbase.py +++ b/wx/lib/pubsub/core/publisherbase.py @@ -8,8 +8,6 @@ from .topicmgr import ( TreeConfig ) -from .. import py2and3 - class PublisherBase: """ @@ -177,7 +175,7 @@ class PublisherBase: if topicName is None: # unsubscribe all listeners from all topics topicsMap = self.__topicMgr._topicsMap - for topicName, topicObj in py2and3.iteritems(topicsMap): + for topicName, topicObj in topicsMap.items(): if topicFilter is None or topicFilter(topicName): tmp = topicObj.unsubscribeAllListeners(listenerFilter) unsubdListeners.extend(tmp) diff --git a/wx/lib/pubsub/core/topicdefnprovider.py b/wx/lib/pubsub/core/topicdefnprovider.py index a60015a8..6aca10fc 100644 --- a/wx/lib/pubsub/core/topicdefnprovider.py +++ b/wx/lib/pubsub/core/topicdefnprovider.py @@ -4,12 +4,11 @@ """ -import os, re, inspect +import os, re, inspect, io from textwrap import TextWrapper, dedent from .. import ( policies, - py2and3 ) from .topicargspec import ( topicArgsFromCallable, @@ -129,7 +128,7 @@ class TopicDefnDeserialClass(ITopicDefnDeserializer): def getNextTopic(self): self.__iterStarted = True try: - topicNameTuple, topicClassObj = py2and3.nextiter(self.__nextTopic) + topicNameTuple, topicClassObj = next(self.__nextTopic) except StopIteration: return None @@ -357,7 +356,7 @@ class TopicDefnProvider(ITopicDefnProvider): return desc, spec def topicNames(self): - return py2and3.iterkeys(self.__topicDefns) + return self.__topicDefns.keys() def getTreeDoc(self): return self.__treeDocs @@ -428,13 +427,13 @@ def exportTopicTreeSpec(moduleName = None, rootTopic=None, bak='bak', moduleDoc= if rootTopic is None: from .. import pub rootTopic = pub.getDefaultTopicMgr().getRootAllTopics() - elif py2and3.isstring(rootTopic): + elif isintance(rootTopic, str): from .. import pub rootTopic = pub.getDefaultTopicMgr().getTopic(rootTopic) # create exporter if moduleName is None: - capture = py2and3.StringIO() + capture = io.StringIO() TopicTreeSpecPrinter(rootTopic, fileObj=capture, treeDoc=moduleDoc) return capture.getvalue() @@ -485,7 +484,7 @@ class TopicTreeSpecPrinter: args = dict(width=width, indentStep=indentStep, treeDoc=treeDoc, footer=footer, fileObj=fileObj) def fmItem(argName, argVal): - if py2and3.isstring(argVal): + if isinstance(argVal, str): MIN_OFFSET = 5 lenAV = width - MIN_OFFSET - len(argName) if lenAV > 0: @@ -493,7 +492,7 @@ class TopicTreeSpecPrinter: elif argName == 'fileObj': argVal = fileObj.__class__.__name__ return '# - %s: %s' % (argName, argVal) - fmtArgs = [fmItem(key, args[key]) for key in sorted(py2and3.iterkeys(args))] + fmtArgs = [fmItem(key, args[key]) for key in sorted(args.keys())] self.__comment = [ '# Automatically generated by %s(**kwargs).' % self.__class__.__name__, '# The kwargs were:', diff --git a/wx/lib/pubsub/core/topicmgr.py b/wx/lib/pubsub/core/topicmgr.py index 10342a48..4247dc2a 100644 --- a/wx/lib/pubsub/core/topicmgr.py +++ b/wx/lib/pubsub/core/topicmgr.py @@ -40,8 +40,6 @@ from .treeconfig import TreeConfig from .topicdefnprovider import ITopicDefnProvider from .topicmgrimpl import getRootTopicSpec -from .. import py2and3 - # --------------------------------------------------------- @@ -255,7 +253,7 @@ class TopicManager: def checkAllTopicsHaveMDS(self): """Check that all topics that have been created for their MDS. Raise a TopicDefnError if one is found that does not have one.""" - for topic in py2and3.itervalues(self._topicsMap): + for topic in self._topicsMap.values(): if not topic.hasMDS(): raise TopicDefnError(topic.getNameTuple()) @@ -287,7 +285,7 @@ class TopicManager: subscribed. Note: the listener can also get messages from any sub-topic of returned list.""" assocTopics = [] - for topicObj in py2and3.itervalues(self._topicsMap): + for topicObj in self._topicsMap.values(): if topicObj.hasListener(listener): assocTopics.append(topicObj) return assocTopics diff --git a/wx/lib/pubsub/core/topicobj.py b/wx/lib/pubsub/core/topicobj.py index edff9584..5cfef56f 100644 --- a/wx/lib/pubsub/core/topicobj.py +++ b/wx/lib/pubsub/core/topicobj.py @@ -4,7 +4,7 @@ Provide the Topic class. :copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE_BSD_Simple.txt for details. """ - +import sys from weakref import ref as weakref @@ -38,8 +38,8 @@ from .topicargspec import ( MessageDataSpecError, ) -from .. import py2and3 - +def getexcobj(): + return sys.exc_info()[1] class Topic(PublisherMixin): """ @@ -140,7 +140,7 @@ class Topic(PublisherMixin): self.__parentTopic()._getListenerSpec()) except MessageDataSpecError: # discard the lower part of the stack trace - exc = py2and3.getexcobj() + exc = getexcobj() raise exc self.__finalize() @@ -242,7 +242,7 @@ class Topic(PublisherMixin): def getSubtopics(self): """Get a list of Topic instances that are subtopics of self.""" - return py2and3.values(self.__subTopics) + return self.__subTopics.values() def getNumListeners(self): """Return number of listeners currently subscribed to topic. This is @@ -262,12 +262,12 @@ class Topic(PublisherMixin): def getListeners(self): """Get a copy of list of listeners subscribed to this topic. Safe to iterate over while listeners get un/subscribed from this topics (such as while sending a message).""" - return py2and3.keys(self.__listeners) + return self.__listeners.keys() def getListenersIter(self): """Get an iterator over listeners subscribed to this topic. Do not use if listeners can be un/subscribed while iterating. """ - return py2and3.iterkeys(self.__listeners) + return self.__listeners.keys() def validate(self, listener): """Checks whether listener could be subscribed to this topic: @@ -337,11 +337,11 @@ class Topic(PublisherMixin): if filter is None: for listener in self.__listeners: listener._unlinkFromTopic_() - unsubd = py2and3.keys(self.__listeners) + unsubd = self.__listeners.keys() self.__listeners = {} else: unsubd = [] - for listener in py2and3.keys(self.__listeners): + for listener in self.__listeners.keys(): if filter(listener): unsubd.append(listener) listener._unlinkFromTopic_() @@ -408,7 +408,7 @@ class Topic(PublisherMixin): handler( listener.name(), topicObj ) self.__handlingUncaughtListenerExc = False except Exception: - exc = py2and3.getexcobj() + exc = getexcobj() #print 'exception raised', exc self.__handlingUncaughtListenerExc = False raise ExcHandlerError(listener.name(), topicObj, exc) @@ -441,7 +441,7 @@ class Topic(PublisherMixin): self.unsubscribeAllListeners() self.__parentTopic = None - for subName, subObj in py2and3.iteritems(self.__subTopics): + for subName, subObj in self.__subTopics.items(): assert isinstance(subObj, Topic) #print 'Unlinking %s from parent' % subObj.getName() subObj.__undefineBranch(topicsMap) diff --git a/wx/lib/pubsub/core/topicutils.py b/wx/lib/pubsub/core/topicutils.py index 4b3d5cec..460b1459 100644 --- a/wx/lib/pubsub/core/topicutils.py +++ b/wx/lib/pubsub/core/topicutils.py @@ -5,15 +5,16 @@ Various utilities used by topic-related modules. :license: BSD, see LICENSE_BSD_Simple.txt for details. """ +import sys from textwrap import TextWrapper, dedent from .topicexc import TopicNameError -from .. import py2and3 - __all__ = [] +def getexcobj(): + return sys.exc_info()[1] UNDERSCORE = '_' # topic name can't start with this # just want something unlikely to clash with user's topic names @@ -81,7 +82,7 @@ def stringize(topicName): topic. Otherwise, assume topicName is a tuple and convert it to to a dotted name i.e. ('a','b','c') => 'a.b.c'. Empty name is not allowed (ValueError). The reverse operation is tupleize(topicName).""" - if py2and3.isstring(topicName): + if isinstance(topicName, str): return topicName if hasattr(topicName, "msgDataSpec"): @@ -90,7 +91,7 @@ def stringize(topicName): try: name = '.'.join(topicName) except Exception: - exc = py2and3.getexcobj() + exc = getexcobj() raise TopicNameError(topicName, str(exc)) return name @@ -105,7 +106,7 @@ def tupleize(topicName): # then better use isinstance(name, tuple) if hasattr(topicName, "msgDataSpec"): topicName = topicName._topicNameStr - if py2and3.isstring(topicName): + if isinstance(topicName, str): topicTuple = tuple(topicName.split('.')) else: topicTuple = tuple(topicName) # assume already tuple of strings diff --git a/wx/lib/pubsub/py2and3.py b/wx/lib/pubsub/py2and3.py deleted file mode 100644 index e00bc680..00000000 --- a/wx/lib/pubsub/py2and3.py +++ /dev/null @@ -1,608 +0,0 @@ -"""Utilities for writing code that runs on Python 2 and 3""" - -# Copyright (c) 2010-2013 Benjamin Peterson -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -import operator -import sys -import types - -__author__ = "Benjamin Peterson " -__version__ = "1.4.1" - - -# Useful for very coarse version differentiation. -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 - -if PY3: - string_types = str, - integer_types = int, - class_types = type, - text_type = str - binary_type = bytes - - MAXSIZE = sys.maxsize -else: - string_types = basestring, - integer_types = (int, long) - class_types = (type, types.ClassType) - text_type = unicode - binary_type = str - - if sys.platform.startswith("java"): - # Jython always uses 32 bits. - MAXSIZE = int((1 << 31) - 1) - else: - # It's possible to have sizeof(long) != sizeof(Py_ssize_t). - class X(object): - def __len__(self): - return 1 << 31 - try: - len(X()) - except OverflowError: - # 32-bit - MAXSIZE = int((1 << 31) - 1) - else: - # 64-bit - MAXSIZE = int((1 << 63) - 1) - del X - - -def _add_doc(func, doc): - """Add documentation to a function.""" - func.__doc__ = doc - - -def _import_module(name): - """Import module, returning the module after the last dot.""" - __import__(name) - return sys.modules[name] - - -class _LazyDescr(object): - - def __init__(self, name): - self.name = name - - def __get__(self, obj, tp): - result = self._resolve() - setattr(obj, self.name, result) - # This is a bit ugly, but it avoids running this again. - delattr(tp, self.name) - return result - - -class MovedModule(_LazyDescr): - - def __init__(self, name, old, new=None): - super(MovedModule, self).__init__(name) - if PY3: - if new is None: - new = name - self.mod = new - else: - self.mod = old - - def _resolve(self): - return _import_module(self.mod) - - -class MovedAttribute(_LazyDescr): - - def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): - super(MovedAttribute, self).__init__(name) - if PY3: - if new_mod is None: - new_mod = name - self.mod = new_mod - if new_attr is None: - if old_attr is None: - new_attr = name - else: - new_attr = old_attr - self.attr = new_attr - else: - self.mod = old_mod - if old_attr is None: - old_attr = name - self.attr = old_attr - - def _resolve(self): - module = _import_module(self.mod) - return getattr(module, self.attr) - - - -class _MovedItems(types.ModuleType): - """Lazy loading of moved objects""" - - -_moved_attributes = [ - MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), - MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), - MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), - MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), - MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("reload_module", "__builtin__", "imp", "reload"), - MovedAttribute("reduce", "__builtin__", "functools"), - MovedAttribute("StringIO", "StringIO", "io"), - MovedAttribute("UserString", "UserString", "collections"), - MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), - MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), - - MovedModule("builtins", "__builtin__"), - MovedModule("configparser", "ConfigParser"), - MovedModule("copyreg", "copy_reg"), - MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), - MovedModule("http_cookies", "Cookie", "http.cookies"), - MovedModule("html_entities", "htmlentitydefs", "html.entities"), - MovedModule("html_parser", "HTMLParser", "html.parser"), - MovedModule("http_client", "httplib", "http.client"), - MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), - MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), - MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), - MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), - MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), - MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), - MovedModule("cPickle", "cPickle", "pickle"), - MovedModule("queue", "Queue"), - MovedModule("reprlib", "repr"), - MovedModule("socketserver", "SocketServer"), - MovedModule("tkinter", "Tkinter"), - MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), - MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), - MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), - MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), - MovedModule("tkinter_tix", "Tix", "tkinter.tix"), - MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), - MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), - MovedModule("tkinter_colorchooser", "tkColorChooser", - "tkinter.colorchooser"), - MovedModule("tkinter_commondialog", "tkCommonDialog", - "tkinter.commondialog"), - MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), - MovedModule("tkinter_font", "tkFont", "tkinter.font"), - MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), - MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", - "tkinter.simpledialog"), - MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), - MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), - MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), - MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("winreg", "_winreg"), -] -for attr in _moved_attributes: - setattr(_MovedItems, attr.name, attr) -del attr - -moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") - - - -class Module_six_moves_urllib_parse(types.ModuleType): - """Lazy loading of moved objects in six.moves.urllib_parse""" - - -_urllib_parse_moved_attributes = [ - MovedAttribute("ParseResult", "urlparse", "urllib.parse"), - MovedAttribute("parse_qs", "urlparse", "urllib.parse"), - MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), - MovedAttribute("urldefrag", "urlparse", "urllib.parse"), - MovedAttribute("urljoin", "urlparse", "urllib.parse"), - MovedAttribute("urlparse", "urlparse", "urllib.parse"), - MovedAttribute("urlsplit", "urlparse", "urllib.parse"), - MovedAttribute("urlunparse", "urlparse", "urllib.parse"), - MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), - MovedAttribute("quote", "urllib", "urllib.parse"), - MovedAttribute("quote_plus", "urllib", "urllib.parse"), - MovedAttribute("unquote", "urllib", "urllib.parse"), - MovedAttribute("unquote_plus", "urllib", "urllib.parse"), - MovedAttribute("urlencode", "urllib", "urllib.parse"), -] -for attr in _urllib_parse_moved_attributes: - setattr(Module_six_moves_urllib_parse, attr.name, attr) -del attr - -sys.modules[__name__ + ".moves.urllib_parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") -sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib.parse") - - -class Module_six_moves_urllib_error(types.ModuleType): - """Lazy loading of moved objects in six.moves.urllib_error""" - - -_urllib_error_moved_attributes = [ - MovedAttribute("URLError", "urllib2", "urllib.error"), - MovedAttribute("HTTPError", "urllib2", "urllib.error"), - MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), -] -for attr in _urllib_error_moved_attributes: - setattr(Module_six_moves_urllib_error, attr.name, attr) -del attr - -sys.modules[__name__ + ".moves.urllib_error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib_error") -sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") - - -class Module_six_moves_urllib_request(types.ModuleType): - """Lazy loading of moved objects in six.moves.urllib_request""" - - -_urllib_request_moved_attributes = [ - MovedAttribute("urlopen", "urllib2", "urllib.request"), - MovedAttribute("install_opener", "urllib2", "urllib.request"), - MovedAttribute("build_opener", "urllib2", "urllib.request"), - MovedAttribute("pathname2url", "urllib", "urllib.request"), - MovedAttribute("url2pathname", "urllib", "urllib.request"), - MovedAttribute("getproxies", "urllib", "urllib.request"), - MovedAttribute("Request", "urllib2", "urllib.request"), - MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), - MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), - MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), - MovedAttribute("BaseHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), - MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), - MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), - MovedAttribute("FileHandler", "urllib2", "urllib.request"), - MovedAttribute("FTPHandler", "urllib2", "urllib.request"), - MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), - MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), - MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), - MovedAttribute("urlretrieve", "urllib", "urllib.request"), - MovedAttribute("urlcleanup", "urllib", "urllib.request"), - MovedAttribute("URLopener", "urllib", "urllib.request"), - MovedAttribute("FancyURLopener", "urllib", "urllib.request"), -] -for attr in _urllib_request_moved_attributes: - setattr(Module_six_moves_urllib_request, attr.name, attr) -del attr - -sys.modules[__name__ + ".moves.urllib_request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib_request") -sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") - - -class Module_six_moves_urllib_response(types.ModuleType): - """Lazy loading of moved objects in six.moves.urllib_response""" - - -_urllib_response_moved_attributes = [ - MovedAttribute("addbase", "urllib", "urllib.response"), - MovedAttribute("addclosehook", "urllib", "urllib.response"), - MovedAttribute("addinfo", "urllib", "urllib.response"), - MovedAttribute("addinfourl", "urllib", "urllib.response"), -] -for attr in _urllib_response_moved_attributes: - setattr(Module_six_moves_urllib_response, attr.name, attr) -del attr - -sys.modules[__name__ + ".moves.urllib_response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib_response") -sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") - - -class Module_six_moves_urllib_robotparser(types.ModuleType): - """Lazy loading of moved objects in six.moves.urllib_robotparser""" - - -_urllib_robotparser_moved_attributes = [ - MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), -] -for attr in _urllib_robotparser_moved_attributes: - setattr(Module_six_moves_urllib_robotparser, attr.name, attr) -del attr - -sys.modules[__name__ + ".moves.urllib_robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib_robotparser") -sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") - - -class Module_six_moves_urllib(types.ModuleType): - """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - parse = sys.modules[__name__ + ".moves.urllib_parse"] - error = sys.modules[__name__ + ".moves.urllib_error"] - request = sys.modules[__name__ + ".moves.urllib_request"] - response = sys.modules[__name__ + ".moves.urllib_response"] - robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] - - -sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") - - -def add_move(move): - """Add an item to six.moves.""" - setattr(_MovedItems, move.name, move) - - -def remove_move(name): - """Remove item from six.moves.""" - try: - delattr(_MovedItems, name) - except AttributeError: - try: - del moves.__dict__[name] - except KeyError: - raise AttributeError("no such move, %r" % (name,)) - - -if PY3: - _meth_func = "__func__" - _meth_self = "__self__" - - _func_closure = "__closure__" - _func_code = "__code__" - _func_defaults = "__defaults__" - _func_globals = "__globals__" - - _iterkeys = "keys" - _itervalues = "values" - _iteritems = "items" - _iterlists = "lists" -else: - _meth_func = "im_func" - _meth_self = "im_self" - - _func_closure = "func_closure" - _func_code = "func_code" - _func_defaults = "func_defaults" - _func_globals = "func_globals" - - _iterkeys = "iterkeys" - _itervalues = "itervalues" - _iteritems = "iteritems" - _iterlists = "iterlists" - - -try: - advance_iterator = next -except NameError: - def advance_iterator(it): - return it.next() -next = advance_iterator - - -try: - callable = callable -except NameError: - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) - - -if PY3: - def get_unbound_function(unbound): - return unbound - - create_bound_method = types.MethodType - - Iterator = object -else: - def get_unbound_function(unbound): - return unbound.im_func - - def create_bound_method(func, obj): - return types.MethodType(func, obj, obj.__class__) - - class Iterator(object): - - def next(self): - return type(self).__next__(self) - - callable = callable -_add_doc(get_unbound_function, - """Get the function out of a possibly unbound function""") - - -get_method_function = operator.attrgetter(_meth_func) -get_method_self = operator.attrgetter(_meth_self) -get_function_closure = operator.attrgetter(_func_closure) -get_function_code = operator.attrgetter(_func_code) -get_function_defaults = operator.attrgetter(_func_defaults) -get_function_globals = operator.attrgetter(_func_globals) - - -def iterkeys(d, **kw): - """Return an iterator over the keys of a dictionary.""" - return iter(getattr(d, _iterkeys)(**kw)) - -def itervalues(d, **kw): - """Return an iterator over the values of a dictionary.""" - return iter(getattr(d, _itervalues)(**kw)) - -def iteritems(d, **kw): - """Return an iterator over the (key, value) pairs of a dictionary.""" - return iter(getattr(d, _iteritems)(**kw)) - -def iterlists(d, **kw): - """Return an iterator over the (key, [values]) pairs of a dictionary.""" - return iter(getattr(d, _iterlists)(**kw)) - - -if PY3: - def b(s): - return s.encode("latin-1") - def u(s): - return s - unichr = chr - if sys.version_info[1] <= 1: - def int2byte(i): - return bytes((i,)) - else: - # This is about 2x faster than the implementation above on 3.2+ - int2byte = operator.methodcaller("to_bytes", 1, "big") - byte2int = operator.itemgetter(0) - indexbytes = operator.getitem - iterbytes = iter - import io - StringIO = io.StringIO - BytesIO = io.BytesIO -else: - def b(s): - return s - def u(s): - return unicode(s, "unicode_escape") - unichr = unichr - int2byte = chr - def byte2int(bs): - return ord(bs[0]) - def indexbytes(buf, i): - return ord(buf[i]) - def iterbytes(buf): - return (ord(byte) for byte in buf) - import StringIO - StringIO = BytesIO = StringIO.StringIO -_add_doc(b, """Byte literal""") -_add_doc(u, """Text literal""") - - -if PY3: - import builtins - exec_ = getattr(builtins, "exec") - - - def reraise(tp, value, tb=None): - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - - - print_ = getattr(builtins, "print") - del builtins - -else: - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - - exec_("""def reraise(tp, value, tb=None): - raise tp, value, tb -""") - - - def print_(*args, **kwargs): - """The new-style print function.""" - fp = kwargs.pop("file", sys.stdout) - if fp is None: - return - def write(data): - if not isinstance(data, basestring): - data = str(data) - fp.write(data) - want_unicode = False - sep = kwargs.pop("sep", None) - if sep is not None: - if isinstance(sep, unicode): - want_unicode = True - elif not isinstance(sep, str): - raise TypeError("sep must be None or a string") - end = kwargs.pop("end", None) - if end is not None: - if isinstance(end, unicode): - want_unicode = True - elif not isinstance(end, str): - raise TypeError("end must be None or a string") - if kwargs: - raise TypeError("invalid keyword arguments to print()") - if not want_unicode: - for arg in args: - if isinstance(arg, unicode): - want_unicode = True - break - if want_unicode: - newline = unicode("\n") - space = unicode(" ") - else: - newline = "\n" - space = " " - if sep is None: - sep = space - if end is None: - end = newline - for i, arg in enumerate(args): - if i: - write(sep) - write(arg) - write(end) - -_add_doc(reraise, """Reraise an exception.""") - - -def with_metaclass(meta, *bases): - """Create a base class with a metaclass.""" - return meta("NewBase", bases, {}) - -def add_metaclass(metaclass): - """Class decorator for creating a class with a metaclass.""" - def wrapper(cls): - orig_vars = cls.__dict__.copy() - orig_vars.pop('__dict__', None) - orig_vars.pop('__weakref__', None) - for slots_var in orig_vars.get('__slots__', ()): - orig_vars.pop(slots_var) - return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper - -def getexcobj(): - return sys.exc_info()[1] - -if PY3: - xrange = range -else: - xrange = xrange - -if PY3: - def keys(dictObj): - return list(dictObj.keys()) - def values(dictObj): - return list(dictObj.values()) - def nextiter(container): - return next(container) -else: - def keys(dictObj): - return dictObj.keys() - def values(dictObj): - return dictObj.values() - def nextiter(container): - return container.next() - -if PY3: - def isstring(obj): - return isinstance(obj, str) -else: - def isstring(obj): - return isinstance(obj, (str, unicode)) - diff --git a/wx/lib/pubsub/utils/misc.py b/wx/lib/pubsub/utils/misc.py index 29a4b931..96394308 100644 --- a/wx/lib/pubsub/utils/misc.py +++ b/wx/lib/pubsub/utils/misc.py @@ -6,8 +6,6 @@ printTreeDocs and printTreeSpec. :license: BSD, see LICENSE_BSD_Simple.txt for details. """ -from __future__ import print_function - import sys __all__ = ('printImported', 'StructMsg', 'Callback', 'Enum' ) diff --git a/wx/lib/pubsub/utils/xmltopicdefnprovider.py b/wx/lib/pubsub/utils/xmltopicdefnprovider.py index e9b4ea34..bca65d16 100644 --- a/wx/lib/pubsub/utils/xmltopicdefnprovider.py +++ b/wx/lib/pubsub/utils/xmltopicdefnprovider.py @@ -45,8 +45,6 @@ of the XML tree. :license: BSD, see LICENSE_BSD_Simple.txt for details. """ -from __future__ import print_function - __author__ = 'Joshua R English' __revision__ = 6 __date__ = '2013-07-27' @@ -58,7 +56,6 @@ from ..core.topicdefnprovider import ( ArgSpecGiven, TOPIC_TREE_FROM_STRING, ) -from .. import py2and3 try: from elementtree import ElementTree as ET @@ -162,7 +159,7 @@ class XmlTopicDefnProvider(ITopicDefnProvider): return self._topics.get(topicNameTuple, (None, None)) def topicNames(self): - return py2and3.iterkeys(self._topics) # dict_keys iter in 3, list in 2 + return self._topics.keys() def getTreeDoc(self): return self._treeDoc @@ -259,7 +256,7 @@ def exportTopicTreeSpecXml(moduleName=None, rootTopic=None, bak='bak', moduleDoc if rootTopic is None: from .. import pub rootTopic = pub.getDefaultTopicTreeRoot() - elif py2and3.isstring(rootTopic): + elif isintance(rootTopic, str): from .. import pub rootTopic = pub.getTopic(rootTopic) diff --git a/wx/lib/rcsizer.py b/wx/lib/rcsizer.py index 6c5ff6e5..ce7d7251 100644 --- a/wx/lib/rcsizer.py +++ b/wx/lib/rcsizer.py @@ -33,9 +33,7 @@ encouraged to switch. import operator import wx -import six -if six.PY3: - from functools import reduce as reduce +from functools import reduce as reduce # After the lib and demo no longer uses this sizer enable this warning... diff --git a/wx/lib/softwareupdate.py b/wx/lib/softwareupdate.py index 55906334..e2831319 100644 --- a/wx/lib/softwareupdate.py +++ b/wx/lib/softwareupdate.py @@ -30,14 +30,8 @@ import wx import sys import os import atexit -import six - -if six.PY3: - from urllib.request import urlopen - from urllib.error import URLError -else: - from urllib2 import urlopen - from urllib2 import URLError +from urllib.request import urlopen +from urllib.error import URLError from wx.lib.dialogs import MultiMessageBox diff --git a/wx/lib/wxcairo/wx_pycairo.py b/wx/lib/wxcairo/wx_pycairo.py index a8dd044d..19a28dd1 100644 --- a/wx/lib/wxcairo/wx_pycairo.py +++ b/wx/lib/wxcairo/wx_pycairo.py @@ -16,7 +16,6 @@ wx.lib.wxcairo implementation functions using PyCairo. """ import wx -from six import PY3 import cairo import ctypes @@ -413,16 +412,10 @@ def _loadPycairoAPI(): if not hasattr(cairo, 'CAPI'): return - if PY3: - PyCapsule_GetPointer = ctypes.pythonapi.PyCapsule_GetPointer - PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] - PyCapsule_GetPointer.restype = ctypes.c_void_p - ptr = PyCapsule_GetPointer(cairo.CAPI, b'cairo.CAPI') - else: - PyCObject_AsVoidPtr = ctypes.pythonapi.PyCObject_AsVoidPtr - PyCObject_AsVoidPtr.argtypes = [ctypes.py_object] - PyCObject_AsVoidPtr.restype = ctypes.c_void_p - ptr = PyCObject_AsVoidPtr(cairo.CAPI) + PyCapsule_GetPointer = ctypes.pythonapi.PyCapsule_GetPointer + PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] + PyCapsule_GetPointer.restype = ctypes.c_void_p + ptr = PyCapsule_GetPointer(cairo.CAPI, b'cairo.CAPI') pycairoAPI = ctypes.cast(ptr, ctypes.POINTER(Pycairo_CAPI)).contents #---------------------------------------------------------------------------- diff --git a/wx/py/filling.py b/wx/py/filling.py index 05bf175f..ccca8434 100644 --- a/wx/py/filling.py +++ b/wx/py/filling.py @@ -2,10 +2,8 @@ the local namespace or any object.""" __author__ = "Patrick K. O'Brien " -# Tags: py3-port import wx -import six from . import dispatcher from . import editwindow @@ -115,13 +113,13 @@ class FillingTree(wx.TreeCtrl): busy = wx.BusyCursor() otype = type(obj) if (isinstance(obj, dict) - or 'BTrees' in six.text_type(otype) + or 'BTrees' in str(otype) and hasattr(obj, 'keys')): return obj d = {} if isinstance(obj, (list, tuple)): for n in range(len(obj)): - key = '[' + six.text_type(n) + ']' + key = '[' + str(n) + ']' d[key] = obj[n] if otype not in COMMONTYPES: for key in introspect.getAttributeNames(obj): @@ -143,14 +141,14 @@ class FillingTree(wx.TreeCtrl): children = self.objGetChildren(obj) if not children: return - keys = sorted(children, key=lambda x: six.text_type(x).lower()) + keys = sorted(children, key=lambda x: str(x).lower()) for key in keys: - itemtext = six.text_type(key) + itemtext = str(key) # Show string dictionary items with single quotes, except # for the first level of items, if they represent a # namespace. if isinstance(obj, dict) \ - and isinstance(key, six.string_types) \ + and isinstance(key, str) \ and (item != self.root or (item == self.root and not self.rootIsNamespace)): itemtext = repr(key) @@ -173,12 +171,12 @@ class FillingTree(wx.TreeCtrl): otype = type(obj) text = '' text += self.getFullName(item) - text += '\n\nType: ' + six.text_type(otype) + text += '\n\nType: ' + str(otype) try: - value = six.text_type(obj) + value = str(obj) except Exception: value = '' - if isinstance(obj, six.string_types): + if isinstance(obj, str): value = repr(obj) text += u'\n\nValue: ' + value if otype not in SIMPLETYPES: @@ -187,7 +185,7 @@ class FillingTree(wx.TreeCtrl): inspect.getdoc(obj).strip() + '"""' except Exception: pass - if isinstance(obj, six.class_types): + if isinstance(obj, type): try: text += '\n\nClass Definition:\n\n' + \ inspect.getsource(obj.__class__) @@ -212,7 +210,7 @@ class FillingTree(wx.TreeCtrl): # Apply dictionary syntax to dictionary items, except the root # and first level children of a namespace. if ((isinstance(obj, dict) - or 'BTrees' in six.text_type(type(obj)) + or 'BTrees' in str(type(obj)) and hasattr(obj, 'keys')) and ((item != self.root and parent != self.root) or (parent == self.root and not self.rootIsNamespace))): diff --git a/wx/py/images.py b/wx/py/images.py index fd46033a..71bee777 100644 --- a/wx/py/images.py +++ b/wx/py/images.py @@ -3,7 +3,7 @@ __author__ = "Patrick K. O'Brien / David Mashburn " import wx -from six import BytesIO +from io import BytesIO def getPyIcon(shellName='PyCrust'): icon = wx.Icon() diff --git a/wx/py/interpreter.py b/wx/py/interpreter.py index 94eea2ec..b73c8a86 100644 --- a/wx/py/interpreter.py +++ b/wx/py/interpreter.py @@ -10,7 +10,6 @@ from code import InteractiveInterpreter, compile_command from . import dispatcher from . import introspect import wx -import six class Interpreter(InteractiveInterpreter): """Interpreter based on code.InteractiveInterpreter.""" @@ -25,7 +24,7 @@ class Interpreter(InteractiveInterpreter): self.stdout = stdout self.stderr = stderr if rawin: - from six.moves import builtins + import builtins builtins.raw_input = rawin del builtins if showInterpIntro: @@ -56,14 +55,6 @@ class Interpreter(InteractiveInterpreter): commandBuffer until we have a complete command. If not, we delete that last list.""" - # In case the command is unicode try encoding it - if not six.PY3: - if type(command) == unicode: - try: - command = command.encode('utf-8') - except UnicodeEncodeError: - pass # otherwise leave it alone - if not self.more: try: del self.commandBuffer[-1] except IndexError: pass diff --git a/wx/py/introspect.py b/wx/py/introspect.py index f2d86dbc..66efba42 100644 --- a/wx/py/introspect.py +++ b/wx/py/introspect.py @@ -9,7 +9,7 @@ import inspect import tokenize import types import wx -from six import BytesIO, PY3, string_types +from io import BytesIO def getAutoCompleteList(command='', locals=None, includeMagic=1, includeSingle=1, includeDouble=1): @@ -180,7 +180,7 @@ def getCallTip(command='', locals=None): try: argspec = str(inspect.signature(obj)) # PY35 or later except AttributeError: - argspec = inspect.getargspec(obj) if not PY3 else inspect.getfullargspec(obj) + argspec = inspect.getfullargspec(obj) argspec = inspect.formatargspec(*argspec) if dropSelf: # The first parameter to a method is a reference to an @@ -270,7 +270,7 @@ def getRoot(command, terminator=None): line = token[4] if tokentype in (tokenize.ENDMARKER, tokenize.NEWLINE): continue - if PY3 and tokentype is tokenize.ENCODING: + if tokentype is tokenize.ENCODING: line = lastline break if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \ @@ -316,7 +316,7 @@ def getTokens(command): """Return list of token tuples for command.""" # In case the command is unicode try encoding it - if isinstance(command, string_types): + if isinstance(command, str): try: command = command.encode('utf-8') except UnicodeEncodeError: @@ -330,13 +330,8 @@ def getTokens(command): # tokens = [token for token in tokenize.generate_tokens(f.readline)] # because of need to append as much as possible before TokenError. try: - if not PY3: - def eater(*args): - tokens.append(args) - tokenize.tokenize_loop(f.readline, eater) - else: - for t in tokenize.tokenize(f.readline): - tokens.append(t) + for t in tokenize.tokenize(f.readline): + tokens.append(t) except tokenize.TokenError: # This is due to a premature EOF, which we expect since we are # feeding in fragments of Python code. diff --git a/wx/py/shell.py b/wx/py/shell.py index 47ced4df..d5b83f3a 100755 --- a/wx/py/shell.py +++ b/wx/py/shell.py @@ -8,7 +8,6 @@ __author__ = "Patrick K. O'Brien " import wx from wx import stc -from six import PY3 import keyword import os @@ -410,7 +409,7 @@ class Shell(editwindow.EditWindow): This sets "close", "exit" and "quit" to a helpful string. """ - from six.moves import builtins + import builtins builtins.close = builtins.exit = builtins.quit = \ 'Click on the close button to leave the application.' builtins.cd = cd @@ -438,12 +437,9 @@ class Shell(editwindow.EditWindow): """Execute the user's PYTHONSTARTUP script if they have one.""" if startupScript and os.path.isfile(startupScript): text = 'Startup script executed: ' + startupScript - if PY3: - self.push('print(%r)' % text) - self.push('with open(%r, "r") as f:\n' - ' exec(f.read())\n' % (startupScript)) - else: - self.push('print(%r); execfile(%r)' % (text, startupScript)) + self.push('print(%r)' % text) + self.push('with open(%r, "r") as f:\n' + ' exec(f.read())\n' % (startupScript)) self.interp.startupScript = startupScript else: self.push('') diff --git a/wx/py/sliceshell.py b/wx/py/sliceshell.py index 1bbc643d..f2d57936 100755 --- a/wx/py/sliceshell.py +++ b/wx/py/sliceshell.py @@ -15,7 +15,6 @@ __author__ += "Patrick K. O'Brien " import wx from wx import stc -from six import PY3 import keyword import os @@ -980,12 +979,7 @@ class SlicesShell(editwindow.EditWindow): This sets "close", "exit" and "quit" to a helpful string. """ - from six import PY3 - if PY3: - import builtins - else: - import __builtin__ - builtins = __builtin__ + import builtins builtins.close = builtins.exit = builtins.quit = \ 'Click on the close button to leave the application.' builtins.cd = cd diff --git a/wx/tools/pywxrc.py b/wx/tools/pywxrc.py index 552fcba1..2dd16a40 100644 --- a/wx/tools/pywxrc.py +++ b/wx/tools/pywxrc.py @@ -31,8 +31,6 @@ Usage: python pywxrc.py -h -o, --output output filename, or - for stdout """ -from __future__ import print_function - import sys, os, getopt, glob, re import xml.dom.minidom as minidom from six import byte2int diff --git a/wx/tools/wxget.py b/wx/tools/wxget.py index 4c74c42f..86a8c2b5 100644 --- a/wx/tools/wxget.py +++ b/wx/tools/wxget.py @@ -26,22 +26,15 @@ Where URL is a file URL and the optional DEST_DIR is a destination directory to download to, (default is to prompt the user). The --trusted option can be used to suppress certificate checks. """ -from __future__ import (division, absolute_import, print_function, unicode_literals) - import sys import os import wx import subprocess import ssl -if sys.version_info >= (3,): - from urllib.error import (HTTPError, URLError) - import urllib.request as urllib2 - import urllib.parse as urlparse -else: - import urllib2 - from urllib2 import (HTTPError, URLError) - import urlparse +from urllib.error import (HTTPError, URLError) +import urllib.request as urllib2 +import urllib.parse as urlparse try: import pip diff --git a/wx/tools/wxget_docs_demo.py b/wx/tools/wxget_docs_demo.py index 0e20618e..d06ecd85 100644 --- a/wx/tools/wxget_docs_demo.py +++ b/wx/tools/wxget_docs_demo.py @@ -26,24 +26,16 @@ launch it. Use: doc|demo --force to force a fresh download. """ -from __future__ import (division, absolute_import, print_function, unicode_literals) - import sys import os import subprocess import webbrowser import tarfile import warnings -if sys.version_info >= (3,): - from urllib.error import HTTPError - import urllib.request as urllib2 - import urllib.parse as urlparse - from urllib.request import pathname2url -else: - import urllib2 - from urllib2 import HTTPError - import urlparse - from urllib import pathname2url +from urllib.error import HTTPError +import urllib.request as urllib2 +import urllib.parse as urlparse +from urllib.request import pathname2url import wx from wx.tools import wxget