From 82750e071b292cb2691a16a923e42121408fb45c Mon Sep 17 00:00:00 2001 From: Alexandre Detiste Date: Wed, 20 Mar 2024 14:39:16 +0100 Subject: [PATCH 1/4] remove usage of six.print_() --- samples/printing/printing.py | 29 +++++++-------- samples/roses/clroses.py | 11 +++--- samples/roses/wxroses.py | 39 +++++++++++---------- samples/simple/events.py | 14 ++++---- wx/lib/pubsub/utils/misc.py | 5 +-- wx/lib/pubsub/utils/xmltopicdefnprovider.py | 4 ++- wx/tools/pywxrc.py | 24 +++++++------ 7 files changed, 67 insertions(+), 59 deletions(-) diff --git a/samples/printing/printing.py b/samples/printing/printing.py index 638d5cde2..8af9a05e2 100644 --- a/samples/printing/printing.py +++ b/samples/printing/printing.py @@ -1,5 +1,6 @@ +from __future__ import print_function + import wx -from six import print_ import os FONTSIZE = 10 @@ -180,7 +181,7 @@ def OnPageSetup(self, evt): data = dlg.GetPageSetupData() self.pdata = wx.PrintData(data.GetPrintData()) # force a copy self.pdata.SetPaperId(data.GetPaperId()) - #print_("paperID %r, paperSize %r" % (self.pdata.GetPaperId(), self.pdata.GetPaperSize())) + #print("paperID %r, paperSize %r" % (self.pdata.GetPaperId(), self.pdata.GetPaperSize())) self.margins = (data.GetMarginTopLeft(), data.GetMarginBottomRight()) dlg.Destroy() @@ -226,20 +227,20 @@ def OnPrintTest(self, evt): dlg = wx.PrintDialog(self, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPrintDialogData() - print_() - print_("GetFromPage:", data.GetFromPage()) - print_("GetToPage:", data.GetToPage()) - print_("GetMinPage:", data.GetMinPage()) - print_("GetMaxPage:", data.GetMaxPage()) - print_("GetNoCopies:", data.GetNoCopies()) - print_("GetAllPages:", data.GetAllPages()) - print_("GetSelection:", data.GetSelection()) - print_("GetCollate:", data.GetCollate()) - print_("GetPrintToFile:", data.GetPrintToFile()) + print() + print("GetFromPage:", data.GetFromPage()) + print("GetToPage:", data.GetToPage()) + print("GetMinPage:", data.GetMinPage()) + print("GetMaxPage:", data.GetMaxPage()) + print("GetNoCopies:", data.GetNoCopies()) + print("GetAllPages:", data.GetAllPages()) + print("GetSelection:", data.GetSelection()) + print("GetCollate:", data.GetCollate()) + print("GetPrintToFile:", data.GetPrintToFile()) self.pdata = wx.PrintData(data.GetPrintData()) - print_() - print_("GetPrinterName:", self.pdata.GetPrinterName()) + print() + print("GetPrinterName:", self.pdata.GetPrinterName()) dlg.Destroy() diff --git a/samples/roses/clroses.py b/samples/roses/clroses.py index a5a878667..f25ac93b2 100644 --- a/samples/roses/clroses.py +++ b/samples/roses/clroses.py @@ -36,8 +36,9 @@ # 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 -from six import print_ # Rose class knows about: # > Generating points and vectors (returning data as a list of points) @@ -151,7 +152,7 @@ def gcd(self, a, b): # update parameters or stop. def restart(self): if self.verbose: - print_('restart: int_state', self.int_state, 'cmd_state', self.cmd_state) + print('restart: int_state', self.int_state, 'cmd_state', self.cmd_state) try: tmp = self.sin_table[0] except: @@ -192,7 +193,7 @@ def resize(self, size, delay): # before initialization is done. def repaint(self, delay): if self.int_state != self.INT_RESIZE: - # print_('repaint after', delay) + # print('repaint after', delay) self.int_state = self.INT_RESIZE self.AppCancelTimer() self.AppAfter(delay, self.clock) @@ -264,7 +265,7 @@ def cmd_step(self): # roses is 0.) def clock(self): if self.int_state == self.INT_IDLE: - # print_('clock called in idle state') + # print('clock called in idle state') delay = 0 elif self.int_state == self.INT_DRAW: line, run = self.roselet() @@ -295,7 +296,7 @@ def clock(self): if delay == 0: if self.verbose: - print_('clock: going idle from state', self.int_state) + print('clock: going idle from state', self.int_state) else: self.AppAfter(delay, self.clock) diff --git a/samples/roses/wxroses.py b/samples/roses/wxroses.py index 7f8e3a7e3..645f56aa9 100644 --- a/samples/roses/wxroses.py +++ b/samples/roses/wxroses.py @@ -68,10 +68,11 @@ # 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 -from six import print_ # Class SpinPanel creates a control that includes both a StaticText widget # which holds the the name of a parameter and a SpinCtrl widget which @@ -109,7 +110,7 @@ def OnSpin(self, event): name = self.st.GetLabel() value = self.sc.GetValue() if verbose: - print_('OnSpin', name, '=', value) + print('OnSpin', name, '=', value) self.callback(name, value) # Call MyFrame.OnSpinback to call clroses @@ -372,10 +373,10 @@ def makeSP(name, labels, statictexts = None): h = max(600, fh) # Change 600 to desired minimum size w = h + fw - rw if verbose: - print_('rose panel size', (rw, rh)) - print_('side panel size', (sw, sh)) - print_(' frame size', (fw, fh)) - print_('Want size', (w,h)) + print('rose panel size', (rw, rh)) + print('side panel size', (sw, sh)) + print(' frame size', (fw, fh)) + print('Want size', (w,h)) self.SetSize((w, h)) self.SupplyControlValues() # Ask clroses to tell us all the defaults self.Show() @@ -386,25 +387,25 @@ def makeSP(name, labels, statictexts = None): # Go/Stop button def OnGoStop(self, event): if verbose: - print_('OnGoStop') + print('OnGoStop') self.cmd_go_stop() # Redraw/Redraw def OnRedraw(self, event): if verbose: - print_('OnRedraw') + print('OnRedraw') self.cmd_redraw() # Backward/Reverse def OnBackward(self, event): if verbose: - print_('OnBackward') + print('OnBackward') self.cmd_backward() # Forward/Skip def OnForward(self, event): if verbose: - print_('OnForward') + print('OnForward') self.cmd_step() @@ -415,7 +416,7 @@ def OnForward(self, event): def AppClear(self): if verbose: - print_('AppClear: clear screen') + print('AppClear: clear screen') self.rose_panel.Clear() def AppCreateLine(self, line): @@ -467,8 +468,8 @@ def AppCmdLabels(self, labels): # Method to provide a single callback after some amount of time. def AppAfter(self, msec, callback): if self.timer_callback: - print_('AppAfter: timer_callback already set!') - # print_('AppAfter:', callback) + print('AppAfter: timer_callback already set!') + # print('AppAfter:', callback) self.timer_callback = callback self.timer.Start(msec, True) @@ -476,14 +477,14 @@ def AppAfter(self, msec, callback): # interest in. def AppCancelTimer(self): self.timer.Stop() - # print_('AppCancelTimer') + # print('AppCancelTimer') self.timer_callback = None # When the timer happens, we come here and jump off to clroses internal code. def OnTimer(self, evt): callback = self.timer_callback self.timer_callback = None - # print_('OnTimer,', callback) + # print('OnTimer,', callback) if callback: callback() # Often calls AppAfter() and sets the callback else: @@ -502,7 +503,7 @@ def TriggerRedraw(self): # Called when data in spin boxes changes. def OnSpinback(self, name, value): if verbose: - print_('OnSpinback', name, value) + print('OnSpinback', name, value) if name == 'Style': self.SetStyle(value) elif name == 'Sincr': @@ -530,7 +531,7 @@ def OnSpinback(self, name, value): elif name == 'Delay': self.SetWaitDelay(value) else: - print_('OnSpinback: Don\'t recognize', name) + print('OnSpinback: Don\'t recognize', name) verbose = 0 # Need some command line options... spin_panels = {} # Hooks to get from rose to panel labels @@ -539,6 +540,6 @@ def OnSpinback(self, name, value): app = wx.App(False) MyFrame() if verbose: - print_('spin_panels', list(spin_panels)) - print_('ctrl_buttons', list(ctrl_buttons)) + print('spin_panels', list(spin_panels)) + print('ctrl_buttons', list(ctrl_buttons)) app.MainLoop() diff --git a/samples/simple/events.py b/samples/simple/events.py index af58312a1..112875bd2 100644 --- a/samples/simple/events.py +++ b/samples/simple/events.py @@ -1,9 +1,9 @@ +from __future__ import print_function import wx -from six import print_ -print_(wx.version()) -#import os; print_('PID:', os.getpid()); raw_input('Ready to start, press enter...') +print(wx.version()) +#import os; print('PID:', os.getpid()); raw_input('Ready to start, press enter...') class MyFrame(wx.Frame): @@ -13,21 +13,21 @@ def __init__(self, *args, **kw): wx.CallAfter(self.after, 1, 2, 3) def after(self, a, b, c): - print_('Called via wx.CallAfter:', a, b, c) + print('Called via wx.CallAfter:', a, b, c) def onSize(self, evt): - print_(repr(evt.Size)) + print(repr(evt.Size)) evt.Skip() class MyApp(wx.App): def OnInit(self): - print_('OnInit') + print('OnInit') frm = MyFrame(None, title="Hello with Events", size=(480,360)) frm.Show() return True def OnExit(self): - print_('OnExit') + print('OnExit') return 0 app = MyApp() diff --git a/wx/lib/pubsub/utils/misc.py b/wx/lib/pubsub/utils/misc.py index 7d7727461..29a4b9311 100644 --- a/wx/lib/pubsub/utils/misc.py +++ b/wx/lib/pubsub/utils/misc.py @@ -6,8 +6,9 @@ :license: BSD, see LICENSE_BSD_Simple.txt for details. """ +from __future__ import print_function + import sys -from .. import py2and3 __all__ = ('printImported', 'StructMsg', 'Callback', 'Enum' ) @@ -16,7 +17,7 @@ def printImported(): """Output a list of pubsub modules imported so far""" ll = sorted([mod for mod in sys.modules if mod.find('pubsub') >= 0]) - py2and3.print_('\n'.join(ll)) + print('\n'.join(ll)) class StructMsg: diff --git a/wx/lib/pubsub/utils/xmltopicdefnprovider.py b/wx/lib/pubsub/utils/xmltopicdefnprovider.py index 20954cc58..e9b4ea349 100644 --- a/wx/lib/pubsub/utils/xmltopicdefnprovider.py +++ b/wx/lib/pubsub/utils/xmltopicdefnprovider.py @@ -45,6 +45,8 @@ :license: BSD, see LICENSE_BSD_Simple.txt for details. """ +from __future__ import print_function + __author__ = 'Joshua R English' __revision__ = 6 __date__ = '2013-07-27' @@ -80,7 +82,7 @@ def _get_elem(elem): try: elem = ET.fromstring(elem) except: - py2and3.print_("Value Error", elem) + print("Value Error", elem) raise ValueError("Cannot convert to element") return elem diff --git a/wx/tools/pywxrc.py b/wx/tools/pywxrc.py index 8596940d1..552fcba17 100644 --- a/wx/tools/pywxrc.py +++ b/wx/tools/pywxrc.py @@ -31,9 +31,11 @@ -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 print_, byte2int +from six import byte2int #---------------------------------------------------------------------- @@ -286,7 +288,7 @@ def MakePythonModule(self, inputFiles, outputFilename, gettextStrings += self.FindStringsInNode(resourceDocument.firstChild) # now write it all out - print_(self.templates.FILE_HEADER, file=outputFile) + print(self.templates.FILE_HEADER, file=outputFile) # Note: Technically it is not legal to have anything other # than ascii for class and variable names, but since the user @@ -295,23 +297,23 @@ def MakePythonModule(self, inputFiles, outputFilename, # later when they try to run the program. if subclasses: subclasses = self.ReplaceBlocks(u"\n".join(subclasses)) - print_(subclasses, file=outputFile) + print(subclasses, file=outputFile) if classes: classes = self.ReplaceBlocks(u"\n".join(classes)) - print_(classes, file=outputFile) + print(classes, file=outputFile) - print_(self.templates.INIT_RESOURE_HEADER, file=outputFile) + print(self.templates.INIT_RESOURE_HEADER, file=outputFile) if embedResources: - print_(self.templates.PREPARE_MEMFS, file=outputFile) + print(self.templates.PREPARE_MEMFS, file=outputFile) resources = u"\n".join(resources) - print_(resources, file=outputFile) + print(resources, file=outputFile) if generateGetText: # gettextStrings is a list of unicode strings as returned by ConvertText conversions = [u' _("%s")' % s for s in gettextStrings] conversion_block = u"\n".join(conversions) conversion_func = self.templates.GETTEXT_DUMMY_FUNC % conversion_block - print_(conversion_func, file=outputFile) + print(conversion_func, file=outputFile) #------------------------------------------------------------------- @@ -327,7 +329,7 @@ def MakeGetTextOutput(self, inputFiles, outputFilename): strings = self.FindStringsInNode(resource) # strings is a list of unicode strings as returned by ConvertText strings = ['_("%s");' % s for s in strings] - print_("\n".join(strings), file=outputFile) + print("\n".join(strings), file=outputFile) #------------------------------------------------------------------- @@ -940,10 +942,10 @@ def main(args=None): except IOError as exc: - print_("%s." % str(exc), file=sys.stderr) + print("%s." % str(exc), file=sys.stderr) else: if outputFilename != "-": - print_("Resources written to %s." % outputFilename, file=sys.stderr) + print("Resources written to %s." % outputFilename, file=sys.stderr) if __name__ == "__main__": main(sys.argv[1:]) From 73a7522b4d473920b970e0cbf0cef5e9c73d09da Mon Sep 17 00:00:00 2001 From: Alexandre Detiste Date: Fri, 22 Mar 2024 00:06:03 +0100 Subject: [PATCH 2/4] remove most of Python2 compatibility code --- build.py | 2 - buildtools/backports/six.py | 952 ------------------ demo/AUI_DockingWindowMgr.py | 2 +- demo/ArtProvider.py | 2 +- demo/ImageFromStream.py | 2 +- demo/Main.py | 22 +- demo/MimeTypesManager.py | 3 +- demo/PropertyGrid.py | 5 +- demo/RichTextCtrl.py | 2 +- demo/SVGImage_Bitmap.py | 3 - demo/SVGImage_Render.py | 3 - demo/agw/FoldPanelBar.py | 3 +- demo/agw/HyperTreeList.py | 6 +- demo/agw/Windows7Explorer_Contents.py | 6 - etg/config.py | 3 - etg/listctrl.py | 5 +- etg/wxdatetime.py | 4 - samples/doodle/superdoodle.py | 3 +- samples/floatcanvas/DrawBot.py | 3 +- samples/html2/webview_sample.py | 2 +- samples/printing/printing.py | 2 - samples/roses/clroses.py | 2 - samples/roses/wxroses.py | 2 - samples/simple/events.py | 2 - sphinxtools/modulehunter.py | 11 +- unittests/test_arraystring.py | 14 +- unittests/test_bitmap.py | 6 +- unittests/test_cmndata.py | 12 +- unittests/test_cursor.py | 6 +- unittests/test_image.py | 43 +- unittests/test_lib_cdate.py | 1 - unittests/test_lib_pubsub_defaultlog.py | 2 +- unittests/test_lib_pubsub_listener.py | 4 - unittests/test_lib_pubsub_notify.py | 2 +- unittests/test_lib_pubsub_notify4.py | 3 +- unittests/test_lib_pubsub_topicmgr.py | 2 +- unittests/test_pgvariant.py | 2 - unittests/test_stream.py | 3 +- unittests/test_string.py | 52 - unittests/test_variant.py | 4 +- unittests/test_window.py | 3 +- unittests/test_wxdatetime.py | 9 +- unittests/wtc.py | 15 +- wx/lib/CDate.py | 1 - wx/lib/agw/artmanager.py | 2 +- wx/lib/agw/aui/auibar.py | 7 +- wx/lib/agw/aui/auibook.py | 9 +- wx/lib/agw/aui/framemanager.py | 14 +- wx/lib/agw/customtreectrl.py | 5 - wx/lib/agw/flatmenu.py | 8 +- wx/lib/agw/flatnotebook.py | 4 +- wx/lib/agw/floatspin.py | 7 +- wx/lib/agw/fmcustomizedlg.py | 7 +- wx/lib/agw/hypertreelist.py | 7 +- wx/lib/agw/persist/persist_constants.py | 5 +- wx/lib/agw/persist/persistencemanager.py | 7 +- wx/lib/agw/ribbon/bar.py | 4 +- wx/lib/agw/ribbon/buttonbar.py | 4 +- wx/lib/agw/rulerctrl.py | 6 +- wx/lib/agw/scrolledthumbnail.py | 13 +- wx/lib/agw/ultimatelistctrl.py | 11 +- wx/lib/agw/xlsgrid.py | 8 +- wx/lib/colourchooser/__init__.py | 2 - wx/lib/colourchooser/pycolourchooser.py | 2 - wx/lib/colourchooser/pycolourslider.py | 2 - wx/lib/colourchooser/pypalette.py | 2 - wx/lib/embeddedimage.py | 4 +- wx/lib/fancytext.py | 15 +- wx/lib/floatcanvas/FCObjects.py | 21 +- wx/lib/floatcanvas/FloatCanvas.py | 3 - wx/lib/floatcanvas/Resources.py | 2 +- wx/lib/floatcanvas/ScreenShot.py | 2 +- wx/lib/graphics.py | 3 +- wx/lib/inspection.py | 3 +- wx/lib/intctrl.py | 20 +- wx/lib/masked/combobox.py | 4 +- wx/lib/masked/ipaddrctrl.py | 3 +- wx/lib/masked/maskededit.py | 39 +- wx/lib/masked/numctrl.py | 3 +- wx/lib/masked/timectrl.py | 7 +- wx/lib/mixins/listctrl.py | 11 +- wx/lib/multisash.py | 5 +- wx/lib/pdfviewer/viewer.py | 6 +- wx/lib/printout.py | 10 +- wx/lib/pubsub/core/callables.py | 8 +- wx/lib/pubsub/core/imp2.py | 3 +- wx/lib/pubsub/core/kwargs/publisher.py | 6 +- wx/lib/pubsub/core/kwargs/topicargspecimpl.py | 7 +- wx/lib/pubsub/core/publisherbase.py | 4 +- wx/lib/pubsub/core/topicdefnprovider.py | 15 +- wx/lib/pubsub/core/topicmgr.py | 6 +- wx/lib/pubsub/core/topicobj.py | 22 +- wx/lib/pubsub/core/topicutils.py | 11 +- wx/lib/pubsub/py2and3.py | 608 ----------- wx/lib/pubsub/utils/misc.py | 2 - wx/lib/pubsub/utils/xmltopicdefnprovider.py | 7 +- wx/lib/rcsizer.py | 4 +- wx/lib/softwareupdate.py | 10 +- wx/lib/wxcairo/wx_pycairo.py | 15 +- wx/py/filling.py | 22 +- wx/py/images.py | 2 +- wx/py/interpreter.py | 11 +- wx/py/introspect.py | 17 +- wx/py/shell.py | 12 +- wx/py/sliceshell.py | 8 +- wx/tools/pywxrc.py | 2 - wx/tools/wxget.py | 13 +- wx/tools/wxget_docs_demo.py | 16 +- 108 files changed, 220 insertions(+), 2144 deletions(-) delete mode 100644 buildtools/backports/six.py delete mode 100644 wx/lib/pubsub/py2and3.py diff --git a/build.py b/build.py index 49d2d98a3..2a508a22b 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 89b2188fd..000000000 --- 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 0faca4f7b..7b62facef 100644 --- a/demo/AUI_DockingWindowMgr.py +++ b/demo/AUI_DockingWindowMgr.py @@ -5,7 +5,7 @@ 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 b890894e7..b5a8fa1f2 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 f428265ec..5a490c5f1 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 db9563629..0c5ea6eea 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 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 @@ def run(self): 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 @@ def __init__(self, name): 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 @@ def LoadDict(self, modID): 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 @@ def LoadDocumentation(self, data): 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 79bc3abed..ca14ff109 100644 --- a/demo/MimeTypesManager.py +++ b/demo/MimeTypesManager.py @@ -18,8 +18,7 @@ # 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 fbef29e31..3e87798c4 100644 --- a/demo/PropertyGrid.py +++ b/demo/PropertyGrid.py @@ -9,7 +9,6 @@ import wx.adv import wx.propgrid as wxpg -from six import exec_ _ = wx.GetTranslation @@ -870,7 +869,7 @@ def OnSetPropertyValues(self,event): 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 @@ def OnAutoFill(self,event): 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 7ac6b1cbb..b88502af6 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 5284291d2..0b7c51d49 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 @@ def __init__(self, parent, bmp_size, *args, **kw): 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 579eb5f25..5c21cf22d 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 @@ def SetRenderer(self, renderer): 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 7d191bc51..62201e5c5 100644 --- a/demo/agw/FoldPanelBar.py +++ b/demo/agw/FoldPanelBar.py @@ -5,8 +5,7 @@ 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 c88e67294..c00a8125e 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 b23df0e1a..c24db9089 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 @@ 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 6a0122232..c2bc87c85 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 dc531a3e5..2c76b003c 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 709f60f6a..eb18c8ed7 100644 --- a/etg/wxdatetime.py +++ b/etg/wxdatetime.py @@ -254,20 +254,16 @@ def fixParseMethod(m, code): 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 0b3d0932c..feff7ff2d 100644 --- a/samples/doodle/superdoodle.py +++ b/samples/doodle/superdoodle.py @@ -11,8 +11,7 @@ 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 52ea41e0a..5bb2a5393 100644 --- a/samples/floatcanvas/DrawBot.py +++ b/samples/floatcanvas/DrawBot.py @@ -14,7 +14,6 @@ """ import wx -from six import moves from math import * try: # see if there is a local FloatCanvas to use @@ -54,7 +53,7 @@ def MakePic(self): 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 22b6489cb..61fbf776f 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 8af9a05e2..bc63744c4 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 f25ac93b2..b6a9ca64c 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 645f56aa9..d6426bff8 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 112875bd2..06ecb0d30 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 6224c8960..f53ad678e 100644 --- a/sphinxtools/modulehunter.py +++ b/sphinxtools/modulehunter.py @@ -22,18 +22,11 @@ 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 bb7a80c9d..cdbb4728f 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 @@ def test_ArrayStringTypemapErrors(self): 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 72132e31e..4cab3d0fb 100644 --- a/unittests/test_bitmap.py +++ b/unittests/test_bitmap.py @@ -2,7 +2,6 @@ from unittests import wtc import wx import os -import six pngFile = os.path.join(os.path.dirname(__file__), 'toucan.png') @@ -58,10 +57,7 @@ def test_Bitmap__nonzero__(self): 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 8bba2b77f..c8d13c68d 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 @@ def test_nonzero(self): 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 6bc100260..63852b3e2 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 @@ def test_Cursor__nonzero__(self): 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 fb3f62021..eaf282573 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 @@ def test_imageGetDataBuffer(self): 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 @@ def test_imageGetAlphaDataBuffer(self): 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 02acd1247..c7825ee69 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 6d9525689..f8208870b 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 2f71fe7c6..95e17ab59 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 DOA: 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 5128ca3f4..4e7bd1df3 100644 --- a/unittests/test_lib_pubsub_notify.py +++ b/unittests/test_lib_pubsub_notify.py @@ -22,7 +22,7 @@ def testNotifyByPrint(self): 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 8d79ba8cf..11d11149c 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 @@ def notifyDelTopic(self, topicName): 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 da0da080a..9ccdec553 100644 --- a/unittests/test_lib_pubsub_topicmgr.py +++ b/unittests/test_lib_pubsub_topicmgr.py @@ -359,7 +359,7 @@ def test1(self): 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 686698c1b..2ca2de31b 100644 --- a/unittests/test_pgvariant.py +++ b/unittests/test_pgvariant.py @@ -3,8 +3,6 @@ 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 e19042d59..18751a8c1 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 e75dc2bfb..a2406ed67 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 @@ 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 d4f9563c4..d7b2f51da 100644 --- a/unittests/test_variant.py +++ b/unittests/test_variant.py @@ -2,8 +2,6 @@ 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 b8132b8e7..fa4669695 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 @@ def test_SimpleWindowCtor(self): 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 62e7d141b..ef56c9121 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 @@ def test_datetime4(self): 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 2ecb3d188..7ce9cb756 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 @@ def waitFor(self, milliseconds): 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 @@ def dict(self): #--------------------------------------------------------------------------- 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 d6d2068bc..4a91dca2f 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 fb8f0e935..797442e92 100644 --- a/wx/lib/agw/artmanager.py +++ b/wx/lib/agw/artmanager.py @@ -6,7 +6,7 @@ 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 ac2ac9167..87f66a707 100644 --- a/wx/lib/agw/aui/auibar.py +++ b/wx/lib/agw/aui/auibar.py @@ -31,9 +31,6 @@ from .aui_utilities import BitmapFromBits, StepColour, GetLabelSize from .aui_utilities import GetBaseColour, MakeDisabledBitmap - -import six - from .aui_constants import * @@ -68,7 +65,7 @@ def __init__(self, command_type, win_id): :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 @@ def __init__(self, command_type=None, win_id=0): 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 d07637fe0..33f1feb3b 100644 --- a/wx/lib/agw/aui/auibook.py +++ b/wx/lib/agw/aui/auibook.py @@ -32,7 +32,6 @@ import datetime from wx.lib.expando import ExpandoTextCtrl -import six from . import tabart as TA @@ -392,7 +391,7 @@ def __init__(self, command_type=None, win_id=0): :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 @@ def __init__(self, command_type=None, win_id=0): 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 @@ def SetActivePage(self, wndOrInt): :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 @@ -4080,7 +4079,7 @@ def SetPageImage(self, page, image): 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 6fc54511e..df5fca14c 100644 --- a/wx/lib/agw/aui/framemanager.py +++ b/wx/lib/agw/aui/framemanager.py @@ -105,8 +105,6 @@ from time import clock as perf_counter import warnings -import six - from . import auibar from . import auibook @@ -987,7 +985,7 @@ def MinSize(self, arg1=None, arg2=None): 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))) @@ -1028,7 +1026,7 @@ def MaxSize(self, arg1=None, arg2=None): 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))) @@ -1071,7 +1069,7 @@ def BestSize(self, arg1=None, arg2=None): 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))) @@ -4122,7 +4120,7 @@ def GetPane(self, item): :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) @@ -6416,7 +6414,7 @@ def UpdateNotebook(self): 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] @@ -9863,7 +9861,7 @@ def MinimizePane(self, paneInfo, mgrUpdate=True): target = paneInfo.name minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap, - _(six.u("Restore %s")) % paneInfo.caption, target=target) + _("Restore %s") % paneInfo.caption, target=target) minimize_toolbar.SetAuiManager(self) minimize_toolbar.Realize() toolpanelname = paneInfo.name + "_min" diff --git a/wx/lib/agw/customtreectrl.py b/wx/lib/agw/customtreectrl.py index 0fbb15c46..8c3097ab0 100644 --- a/wx/lib/agw/customtreectrl.py +++ b/wx/lib/agw/customtreectrl.py @@ -349,8 +349,6 @@ def __init__(self, parent): Latest Revision: Helio Guilherme @ 09 Aug 2018, 21.35 GMT -Version 2.7 - """ # Version Info @@ -359,9 +357,6 @@ def __init__(self, parent): 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 aba6d27ed..7971d113e 100644 --- a/wx/lib/agw/flatmenu.py +++ b/wx/lib/agw/flatmenu.py @@ -200,8 +200,6 @@ def CreateMenu(self): import wx.lib.colourutils as colourutils -import six - from .fmcustomizedlg import FMCustomizeDlg from .artmanager import ArtManager, DCSaver from .fmresources import * @@ -590,7 +588,7 @@ def ConvertToBitmap(self, xpm, alpha=None): else: - stream = six.BytesIO(xpm) + stream = io.BytesIO(xpm) img = wx.Image(stream) return wx.Bitmap(img) @@ -2226,7 +2224,7 @@ def __init__(self, titleOrMenu="", menu=None, state=ControlNormal, cmd=wx.ID_ANY :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 @@ def CreateMoreMenu(self): 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 df0b7415e..0abdf6d5e 100644 --- a/wx/lib/agw/flatnotebook.py +++ b/wx/lib/agw/flatnotebook.py @@ -192,8 +192,6 @@ def CreatePage(self, notebook, caption): 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 @@ def GetPageText(self, page): 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 cb6be099c..57afe5e57 100644 --- a/wx/lib/agw/floatspin.py +++ b/wx/lib/agw/floatspin.py @@ -177,10 +177,7 @@ def __init__(self, parent): 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 @@ def __init__(self, value=0, precision=DEFAULT_PRECISION): 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 e7b063079..4a1c407a9 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 60ec7435a..f373df4c0 100644 --- a/wx/lib/agw/hypertreelist.py +++ b/wx/lib/agw/hypertreelist.py @@ -302,9 +302,6 @@ def __init__(self): 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 - # Version Info __version__ = "1.4" @@ -453,7 +450,7 @@ def __init__(self, input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, :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 @@ -3662,7 +3659,7 @@ def OnAcceptEdit(self, value): 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 1f454fa60..a5f266527 100644 --- a/wx/lib/agw/persist/persist_constants.py +++ b/wx/lib/agw/persist/persist_constants.py @@ -12,7 +12,6 @@ import wx import wx.dataview as dv -import six # ----------------------------------------------------------------------------------- # # PersistenceManager styles @@ -33,14 +32,14 @@ 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 a787d4eb5..d448fffbf 100644 --- a/wx/lib/agw/persist/persistencemanager.py +++ b/wx/lib/agw/persist/persistencemanager.py @@ -35,7 +35,6 @@ import wx import wx.adv -import six from .persist_handlers import FindHandler, HasCtrlHandler @@ -44,7 +43,7 @@ # ----------------------------------------------------------------------------------- # -class PersistentObject(object): +class PersistentObject: """ :class:`PersistentObject`: ABC for anything persistent. @@ -785,10 +784,10 @@ def DoSaveValue(self, obj, keyName, value): 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 b0d28776d..9bee1b942 100644 --- a/wx/lib/agw/ribbon/bar.py +++ b/wx/lib/agw/ribbon/bar.py @@ -98,8 +98,6 @@ import wx from functools import cmp_to_key -import six - from .control import RibbonControl from .art_internal import RibbonPageTabInfo @@ -607,7 +605,7 @@ def SetActivePageByPage(self, page): 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 577da6935..8df44b016 100644 --- a/wx/lib/agw/ribbon/buttonbar.py +++ b/wx/lib/agw/ribbon/buttonbar.py @@ -46,8 +46,6 @@ import wx -import six - from .control import RibbonControl from .art import * @@ -345,7 +343,7 @@ def InsertButton(self, pos, button_id, label, bitmap, bitmap_small=wx.NullBitmap 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 b13ae51a5..c2aeca8f1 100644 --- a/wx/lib/agw/rulerctrl.py +++ b/wx/lib/agw/rulerctrl.py @@ -153,6 +153,7 @@ def __init__(self, parent): """ +import io import wx import math import zlib @@ -166,9 +167,6 @@ def __init__(self, parent): 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 bfb1dd139..2d8423071 100644 --- a/wx/lib/agw/scrolledthumbnail.py +++ b/wx/lib/agw/scrolledthumbnail.py @@ -173,18 +173,15 @@ def ShowDir(self, dir): # 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 @@ def getDataTR(): 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 289d185ad..16dcc0c14 100644 --- a/wx/lib/agw/ultimatelistctrl.py +++ b/wx/lib/agw/ultimatelistctrl.py @@ -236,11 +236,10 @@ def __init__(self, parent): 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 @@ def __init__(self, parent): 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 @@ def Append(self, entry): 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 c8676c664..7583a2a34 100644 --- a/wx/lib/agw/xlsgrid.py +++ b/wx/lib/agw/xlsgrid.py @@ -250,8 +250,6 @@ def __init__(self): 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 @@ def FormatString(self, value, isDate, format_str): 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 b149067fa..31ddf5178 100644 --- a/wx/lib/colourchooser/__init__.py +++ b/wx/lib/colourchooser/__init__.py @@ -12,8 +12,6 @@ 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 124376483..6c3beae87 100644 --- a/wx/lib/colourchooser/pycolourchooser.py +++ b/wx/lib/colourchooser/pycolourchooser.py @@ -12,8 +12,6 @@ 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 f7f043a0f..b88cd5276 100644 --- a/wx/lib/colourchooser/pycolourslider.py +++ b/wx/lib/colourchooser/pycolourslider.py @@ -16,8 +16,6 @@ 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 71b9fc2df..cb81d2b58 100644 --- a/wx/lib/colourchooser/pypalette.py +++ b/wx/lib/colourchooser/pypalette.py @@ -16,8 +16,6 @@ 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 116de595f..6ba4674e3 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 @@ 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 ee78f2a6d..862cc1335 100644 --- a/wx/lib/fancytext.py +++ b/wx/lib/fancytext.py @@ -58,7 +58,6 @@ class StaticFancyText(self, window, id, text, background, ...) import sys import wx -import six import xml.parsers.expat @@ -255,8 +254,6 @@ def getCurrentPen(self): def renderCharacterData(self, data, x, y): raise NotImplementedError() -from six import PY3 - def _addGreek(): alpha = 0xE1 Alpha = 0xC1 @@ -265,10 +262,7 @@ def end(self): 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 start(self, attrs, code=chr(alpha+i)): 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 bf307bdc9..1ddc62b13 100644 --- a/wx/lib/floatcanvas/FCObjects.py +++ b/wx/lib/floatcanvas/FCObjects.py @@ -17,7 +17,6 @@ import sys import wx -import six import numpy as N @@ -228,14 +227,8 @@ def Bind(self, Event, CallBackFun): 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 @@ def Bind(self, Event, CallBackFun): 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 a0c316cd3..8494be93f 100644 --- a/wx/lib/floatcanvas/FloatCanvas.py +++ b/wx/lib/floatcanvas/FloatCanvas.py @@ -42,8 +42,6 @@ """ -from __future__ import division - import sys mac = sys.platform.startswith("darwin") @@ -53,7 +51,6 @@ 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 7235c456d..0065e079d 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 e26d856a7..3ac33b90b 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 f57f016f1..4dedd8c96 100644 --- a/wx/lib/graphics.py +++ b/wx/lib/graphics.py @@ -38,7 +38,6 @@ """ import math -import six import wx import wx.lib.wxcairo as wxcairo @@ -1886,7 +1885,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 eddf576cc..652763e32 100644 --- a/wx/lib/inspection.py +++ b/wx/lib/inspection.py @@ -28,7 +28,6 @@ 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 @@ def UpdateInfo(self, obj): 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 c4ca9ea90..f1740cc1a 100644 --- a/wx/lib/intctrl.py +++ b/wx/lib/intctrl.py @@ -47,11 +47,7 @@ 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 @@ def __init__ ( 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 @@ def __init__ ( 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 @@ def IsInBounds(self, value=None): 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 @@ def _toGUI( self, value ): 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 f9afb1f77..484368c71 100644 --- a/wx/lib/masked/combobox.py +++ b/wx/lib/masked/combobox.py @@ -478,7 +478,7 @@ def Append( self, choice, clientData=None ): 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 @@ def _OnAutoSelect(self, field, match_index=None): # 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 0ea398e06..a20f8da94 100644 --- a/wx/lib/masked/ipaddrctrl.py +++ b/wx/lib/masked/ipaddrctrl.py @@ -23,7 +23,6 @@ """ 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 @@ def SetValue(self, value): """ ## 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 23391c282..87335d427 100644 --- a/wx/lib/masked/maskededit.py +++ b/wx/lib/masked/maskededit.py @@ -813,7 +813,6 @@ class TimeCtrl( BaseMaskedTextCtrl, TimeCtrlAccessorsMixin ): 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 @@ def _ValidateParameters(self, **kwargs): 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 @@ def SetCtrlParameters(self, **kwargs): 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 @@ def _OnChar(self, event): 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 @@ def _getAllowedChars(self, pos): 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 @@ def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False) 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 @@ def _validatePaste(self, paste_text, sel_start, sel_to, raise_on_invalid=False): 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 @@ def _Paste( self, value=None, raise_on_invalid=False, just_return_value=False ): 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 ac659c260..d0177d190 100644 --- a/wx/lib/masked/numctrl.py +++ b/wx/lib/masked/numctrl.py @@ -401,7 +401,6 @@ import copy import wx -import six from sys import maxsize MAXINT = maxsize # (constants should be in upper case) @@ -1641,7 +1640,7 @@ def _toGUI( self, value, apply_limits = True ): ## 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 6ca738d3b..32c1d6190 100644 --- a/wx/lib/masked/timectrl.py +++ b/wx/lib/masked/timectrl.py @@ -281,7 +281,6 @@ import copy import wx -import six from wx.tools.dbg import Logger from wx.lib.masked import Field, BaseMaskedTextCtrl @@ -762,8 +761,8 @@ def GetWxDateTime(self, value=None): ## 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 @@ def __validateValue( self, value ): 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 fe91d7132..2d55ee858 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 @@ def __ColumnSorter(self, key1, key2): 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 487c8aaba..a55c7684b 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 @@ def GetSaveData(self): 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 @@ def GetSaveData(self): 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 4c41cfba9..e37ad7fde 100644 --- a/wx/lib/pdfviewer/viewer.py +++ b/wx/lib/pdfviewer/viewer.py @@ -30,7 +30,7 @@ import types import copy import shutil -from six import BytesIO, string_types +from io import BytesIO import wx @@ -199,7 +199,7 @@ def create_fileobject(filename): 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 @@ -483,7 +483,7 @@ def __init__(self, parent, pdf_file): 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 fitz.open pathname = pdf_file self.pdfdoc = fitz.open(pathname) diff --git a/wx/lib/printout.py b/wx/lib/printout.py index abc42c60a..4c68be68c 100644 --- a/wx/lib/printout.py +++ b/wx/lib/printout.py @@ -27,9 +27,7 @@ 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 @@ def AdjustValues(self): 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 @@ def AdjustValues(self): 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 @@ def PrintRow(self, row_val, draw = True, align = wx.ALIGN_LEFT): 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 7e798c544..c6bb3fdd2 100644 --- a/wx/lib/pubsub/core/callables.py +++ b/wx/lib/pubsub/core/callables.py @@ -11,13 +11,14 @@ :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 c4641e333..933c7b34b 100644 --- a/wx/lib/pubsub/core/imp2.py +++ b/wx/lib/pubsub/core/imp2.py @@ -7,14 +7,13 @@ """ 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 37c28d8c2..bda42fc5e 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 SenderTooManyKwargs(RuntimeError): 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 @@ def sendMessage(self, _topicName, **kwarg): 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 73120d5c2..ea9817f1e 100644 --- a/wx/lib/pubsub/core/kwargs/topicargspecimpl.py +++ b/wx/lib/pubsub/core/kwargs/topicargspecimpl.py @@ -9,7 +9,6 @@ from .topicutils import (stringize, WeakNone) from .validatedefnargs import verifySubset -from .. import py2and3 ### Exceptions raised during check() from sendMessage() @@ -101,7 +100,7 @@ def setArgsDocs(self, docs): """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 @@ def check(self, msgKwargs): 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 b48e3989c..129f93881 100644 --- a/wx/lib/pubsub/core/publisherbase.py +++ b/wx/lib/pubsub/core/publisherbase.py @@ -8,8 +8,6 @@ TreeConfig ) -from .. import py2and3 - class PublisherBase: """ @@ -177,7 +175,7 @@ def unsubAll(self, topicName = None, 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 a60015a86..6aca10fc5 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 @@ def getTreeDoc(self): 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 @@ def getDefn(self, topicNameTuple): 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 @@ def __init__(self, rootTopic=None, fileObj=None, width=70, indentStep=4, 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 @@ def fmItem(argName, argVal): 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 10342a486..4247dc2a5 100644 --- a/wx/lib/pubsub/core/topicmgr.py +++ b/wx/lib/pubsub/core/topicmgr.py @@ -40,8 +40,6 @@ from .topicdefnprovider import ITopicDefnProvider from .topicmgrimpl import getRootTopicSpec -from .. import py2and3 - # --------------------------------------------------------- @@ -255,7 +253,7 @@ def hasTopicDefinition(self, name): 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 @@ def getTopicsSubscribed(self, listener): 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 edff95848..5cfef56fc 100644 --- a/wx/lib/pubsub/core/topicobj.py +++ b/wx/lib/pubsub/core/topicobj.py @@ -4,7 +4,7 @@ :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 @@ MessageDataSpecError, ) -from .. import py2and3 - +def getexcobj(): + return sys.exc_info()[1] class Topic(PublisherMixin): """ @@ -140,7 +140,7 @@ def setMsgArgSpec(self, argsDocs, required=()): 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 @@ def getSubtopic(self, relName): 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 @@ def hasListeners(self): 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 @@ def unsubscribeAllListeners(self, filter=None): 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 @@ def __sendMessage(self, data, topicObj, iterState): 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 @@ def __undefineBranch(self, topicsMap): 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 4b3d5cecb..460b14594 100644 --- a/wx/lib/pubsub/core/topicutils.py +++ b/wx/lib/pubsub/core/topicutils.py @@ -5,15 +5,16 @@ :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 e00bc6804..000000000 --- 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 29a4b9311..963943087 100644 --- a/wx/lib/pubsub/utils/misc.py +++ b/wx/lib/pubsub/utils/misc.py @@ -6,8 +6,6 @@ :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 e9b4ea349..bca65d169 100644 --- a/wx/lib/pubsub/utils/xmltopicdefnprovider.py +++ b/wx/lib/pubsub/utils/xmltopicdefnprovider.py @@ -45,8 +45,6 @@ :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 @@ ArgSpecGiven, TOPIC_TREE_FROM_STRING, ) -from .. import py2and3 try: from elementtree import ElementTree as ET @@ -162,7 +159,7 @@ def getDefn(self, topicNameTuple): 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 6c5ff6e5d..ce7d72515 100644 --- a/wx/lib/rcsizer.py +++ b/wx/lib/rcsizer.py @@ -33,9 +33,7 @@ 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 55906334b..e2831319a 100644 --- a/wx/lib/softwareupdate.py +++ b/wx/lib/softwareupdate.py @@ -30,14 +30,8 @@ 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 a8dd044d8..19a28dd13 100644 --- a/wx/lib/wxcairo/wx_pycairo.py +++ b/wx/lib/wxcairo/wx_pycairo.py @@ -16,7 +16,6 @@ """ 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 d57f07b7e..39c92f1b8 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 @@ def objGetChildren(self, obj): 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): @@ -140,14 +138,14 @@ def addChildren(self, item): 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) @@ -170,12 +168,12 @@ def display(self): 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: @@ -184,7 +182,7 @@ def display(self): 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__) @@ -209,7 +207,7 @@ def getFullName(self, item, partial=''): # 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 fd46033a3..71bee7779 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 94eea2ec6..b73c8a86d 100644 --- a/wx/py/interpreter.py +++ b/wx/py/interpreter.py @@ -10,7 +10,6 @@ from . import dispatcher from . import introspect import wx -import six class Interpreter(InteractiveInterpreter): """Interpreter based on code.InteractiveInterpreter.""" @@ -25,7 +24,7 @@ def __init__(self, locals=None, rawin=None, 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 @@ def push(self, command, astMod=None): 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 f2d86dbc7..66efba428 100644 --- a/wx/py/introspect.py +++ b/wx/py/introspect.py @@ -9,7 +9,7 @@ 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 47ced4df7..d5b83f3a8 100755 --- a/wx/py/shell.py +++ b/wx/py/shell.py @@ -8,7 +8,6 @@ import wx from wx import stc -from six import PY3 import keyword import os @@ -410,7 +409,7 @@ def setBuiltinKeywords(self): 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 @@ def execStartupScript(self, startupScript): """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 1bbc643d7..f2d57936e 100755 --- a/wx/py/sliceshell.py +++ b/wx/py/sliceshell.py @@ -15,7 +15,6 @@ import wx from wx import stc -from six import PY3 import keyword import os @@ -980,12 +979,7 @@ def setBuiltinKeywords(self): 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 552fcba17..2dd16a402 100644 --- a/wx/tools/pywxrc.py +++ b/wx/tools/pywxrc.py @@ -31,8 +31,6 @@ -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 4c74c42f2..86a8c2b5e 100644 --- a/wx/tools/wxget.py +++ b/wx/tools/wxget.py @@ -26,22 +26,15 @@ 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 0e20618e0..d06ecd856 100644 --- a/wx/tools/wxget_docs_demo.py +++ b/wx/tools/wxget_docs_demo.py @@ -26,24 +26,16 @@ 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 From 62fa5d848357d0aee9206939b1ded81dfceee0e5 Mon Sep 17 00:00:00 2001 From: Alexandre Detiste Date: Fri, 22 Mar 2024 00:25:15 +0100 Subject: [PATCH 3/4] remove more Python2 hybridation --- build.py | 9 +----- buildtools/build_wxwidgets.py | 8 ++--- buildtools/config.py | 31 ++++--------------- buildtools/distutils_hacks.py | 2 +- etg/rawbmp.py | 7 ++--- etgtools/extractors.py | 8 ++--- etgtools/generators.py | 15 ++-------- etgtools/sphinx_generator.py | 23 ++++++-------- etgtools/tweaker_tools.py | 10 ++----- packaging/setup.py | 11 +++---- sphinxtools/inheritance.py | 8 ++--- sphinxtools/librarydescription.py | 19 ++---------- sphinxtools/modulehunter.py | 22 ++++---------- sphinxtools/postprocess.py | 7 ++--- sphinxtools/utilities.py | 25 +++------------- wx/lib/activexwrapper.py | 2 +- wx/lib/agw/aui/aui_constants.py | 16 ++-------- wx/py/sliceshell.py | 9 ++---- wx/py/tests/test_introspect.py | 50 ------------------------------- wx/svg/_nanosvg.pyx | 2 -- wx/tools/img2py.py | 5 +--- 21 files changed, 54 insertions(+), 235 deletions(-) diff --git a/build.py b/build.py index 2a508a22b..9c5aa2472 100755 --- a/build.py +++ b/build.py @@ -50,10 +50,6 @@ import buildtools.version as version -# which version of Python is running this script -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 - # defaults PYVER = '2.7' @@ -1070,7 +1066,7 @@ def _removeSidebar(path): tag = soup.find('div', 'document') if tag: tag.attrs['class'] = ['document-no-sidebar'] - text = unicode(soup) if PY2 else str(soup) + text = str(soup) with textfile_open(filename, 'wt') as f: f.write(text) @@ -1484,9 +1480,6 @@ def cmd_build_wx(options, args): if options.jom: build_options.append('--jom') - if PY2: - build_options.append('--no_dpi_aware') - else: # Platform is something other than MSW if options.osx_carbon: diff --git a/buildtools/build_wxwidgets.py b/buildtools/build_wxwidgets.py index ea57e19d1..d1ec6b852 100644 --- a/buildtools/build_wxwidgets.py +++ b/buildtools/build_wxwidgets.py @@ -18,8 +18,6 @@ from buildtools import builder from buildtools.config import getVisCVersion -PY3 = sys.version_info[0] == 3 - # builder object wxBuilder = None @@ -421,8 +419,7 @@ def main(wxDir, args): setupFile = os.path.join(mswIncludeDir, "setup.h") with open(setupFile, "rb") as f: setupText = f.read() - if PY3: - setupText = setupText.decode('utf-8') + setupText = setupText.decode('utf-8') for flag in flags: setupText, subsMade = re.subn(flag + "\s+?\d", "%s %s" % (flag, flags[flag]), setupText) @@ -431,8 +428,7 @@ def main(wxDir, args): sys.exit(1) with open(setupFile, "wb") as f: - if PY3: - setupText = setupText.encode('utf-8') + setupText = setupText.encode('utf-8') f.write(setupText) args = [] diff --git a/buildtools/config.py b/buildtools/config.py index 34418dae3..4b3e659f9 100644 --- a/buildtools/config.py +++ b/buildtools/config.py @@ -482,18 +482,8 @@ def build_locale_dir(self, destdir, verbose=1): def build_locale_list(self, srcdir): # get a list of all files under the srcdir, to be used for install_data - if sys.version_info[0] == 2: - def walk_helper(lst, dirname, files): - for f in files: - filename = opj(dirname, f) - if not os.path.isdir(filename): - lst.append( (dirname, [filename]) ) - file_list = [] - os.path.walk(srcdir, walk_helper, file_list) - return file_list - else: - # TODO: Python3 version using os.walk generator - return [] + # TODO: Python3 version using os.walk generator + return [] def find_data_files(self, srcdir, *wildcards, **kw): @@ -897,8 +887,7 @@ def runcmd(cmd, getOutput=False, echoCmd=True, fatal=True, onError=None): if getOutput: outputEncoding = 'cp1252' if sys.platform == 'win32' else 'utf-8' output = sp.stdout.read() - if sys.version_info > (3,): - output = output.decode(outputEncoding) + output = output.decode(outputEncoding) output = output.rstrip() rval = sp.wait() @@ -917,11 +906,8 @@ def runcmd(cmd, getOutput=False, echoCmd=True, fatal=True, onError=None): def myExecfile(filename, ns): - if sys.version_info < (3,): - execfile(filename, ns) - else: - with open(filename, 'r') as f: - exec(f.read(), ns) + with open(filename, 'r') as f: + exec(f.read(), ns) def textfile_open(filename, mode='rt'): @@ -931,12 +917,7 @@ def textfile_open(filename, mode='rt'): mode parameter must include the 't' to put the stream into text mode. """ assert 't' in mode - if sys.version_info < (3,): - import codecs - mode = mode.replace('t', '') - return codecs.open(filename, mode, encoding='utf-8') - else: - return open(filename, mode, encoding='utf-8') + return open(filename, mode, encoding='utf-8') def getSipFiles(names): diff --git a/buildtools/distutils_hacks.py b/buildtools/distutils_hacks.py index 3626e9864..9cf25aae5 100644 --- a/buildtools/distutils_hacks.py +++ b/buildtools/distutils_hacks.py @@ -311,7 +311,7 @@ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): # into the .pyd files as expected. So we'll strip out that option via # a monkey-patch of the msvc9compiler.MSVCCompiler.initialize method. -if os.name == 'nt' and sys.version_info >= (2,6): +if os.name == 'nt': import distutils.msvc9compiler _orig_initialize = distutils.msvc9compiler.MSVCCompiler.initialize diff --git a/etg/rawbmp.py b/etg/rawbmp.py index 699c8d88e..bc464456f 100644 --- a/etg/rawbmp.py +++ b/etg/rawbmp.py @@ -122,13 +122,10 @@ def __repr__(self): X = property(lambda self: x) Y = property(lambda self: y) - import sys - rangeFunc = range if sys.version_info >= (3,) else xrange - pf = PixelFacade() - for y in rangeFunc(height): + for y in range(height): pixels.MoveTo(self, 0, y) - for x in rangeFunc(width): + for x in range(width): # We always generate the same pf instance, but it # accesses the pixels object which we use to iterate # over the pixel buffer. diff --git a/etgtools/extractors.py b/etgtools/extractors.py index 5ae1361f9..072a9672a 100644 --- a/etgtools/extractors.py +++ b/etgtools/extractors.py @@ -28,7 +28,7 @@ # methods, functions and other items in the C/C++ API being wrapped. #--------------------------------------------------------------------------- -class BaseDef(object): +class BaseDef: """ The base class for all element types and provides the common attributes and functions that they all share. @@ -1684,11 +1684,7 @@ def flattenNode(node, rstrip=True): # TODO: can we just use ElementTree.tostring for this function? if node is None: return "" - if sys.version_info < (3,): - strclass = basestring - else: - strclass = str - if isinstance(node, strclass): + if isinstance(node, str): return node text = node.text or "" for n in node: diff --git a/etgtools/generators.py b/etgtools/generators.py index 7b164c881..848d8b04b 100644 --- a/etgtools/generators.py +++ b/etgtools/generators.py @@ -97,13 +97,7 @@ def wrapText(text): # in the StringIO import io class Utf8EncodingStream(io.StringIO): - if sys.version_info < (3,): - def write(self, text): - if isinstance(text, str): - text = text.decode('utf-8') - return io.StringIO.write(self, text) - - + pass def textfile_open(filename, mode='rt'): @@ -113,12 +107,7 @@ def textfile_open(filename, mode='rt'): mode parameter must include the 't' to put the stream into text mode. """ assert 't' in mode - if sys.version_info < (3,): - import codecs - mode = mode.replace('t', '') - return codecs.open(filename, mode, encoding='utf-8') - else: - return open(filename, mode, encoding='utf-8') + return open(filename, mode, encoding='utf-8') #--------------------------------------------------------------------------- diff --git a/etgtools/sphinx_generator.py b/etgtools/sphinx_generator.py index 88591dba6..b64ae2f33 100644 --- a/etgtools/sphinx_generator.py +++ b/etgtools/sphinx_generator.py @@ -20,12 +20,7 @@ import shutil import textwrap -if sys.version_info < (3, ): - from StringIO import StringIO - string_base = basestring -else: - from io import StringIO - string_base = str +from io import StringIO import xml.etree.ElementTree as et @@ -146,7 +141,7 @@ def GetTag(self, tag_name): :returns: The element text for the input `tag_name` or ``None``. """ - if isinstance(self.element, string_base): + if isinstance(self.element, str): return None return self.element.get(tag_name) @@ -268,7 +263,7 @@ def Join(self, with_tail=True): if self.element is None: return text - if isinstance(self.element, string_base): + if isinstance(self.element, str): text = self.element else: text, tail = self.element.text, self.element.tail @@ -1381,7 +1376,7 @@ def AddCode(self, element): if tag == 'sp': self.snippet += ' ' - if isinstance(element, string_base): + if isinstance(element, str): self.snippet += element else: if element.text: @@ -2006,7 +2001,7 @@ def __init__(self, xml_item, is_overload=False, share_docstrings=False): # Some of the Extractors (xml item) will set deprecated themselves, in which case it is set as a # non-empty string. In such cases, this branch will insert a deprecated section into the xml tree # so that the Node Tree (see classes above) will generate the deprecated tag on their own in self.RecurseXML - if hasattr(xml_item, 'deprecated') and xml_item.deprecated and isinstance(xml_item.deprecated, string_base): + if hasattr(xml_item, 'deprecated') and xml_item.deprecated and isinstance(xml_item.deprecated, str): element = et.Element('deprecated', kind='deprecated') element.text = xml_item.deprecated @@ -2128,7 +2123,7 @@ def RecurseXML(self, element, parent): if element is None: return Node('', parent) - if isinstance(element, string_base): + if isinstance(element, str): rest_class = Paragraph(element, parent, self.kind) return rest_class @@ -2754,7 +2749,7 @@ def DumpEnum(self, write): name = convertToPython(name) stream.write('%-80s' % name) - if not isinstance(docstrings, string_base): + if not isinstance(docstrings, str): rest_class = self.RecurseXML(docstrings, self.root) docstrings = rest_class.Join() @@ -3394,7 +3389,7 @@ def createMemberVarDescription(self, memberVar): brief = memberVar.briefDoc briefDoc = None - if not isinstance(brief, string_base): + if not isinstance(brief, str): docstring = XMLDocString(memberVar) #docstring.current_module = self.current_module briefDoc = docstring.GetBrief() @@ -3541,7 +3536,7 @@ def getName(self, method): simple_docs = convertToPython(method.pyDocstring) else: brief = method.briefDoc - if not isinstance(brief, string_base): + if not isinstance(brief, str): docstring = XMLDocString(method) docstring.kind = 'method' docstring.current_module = self.current_module diff --git a/etgtools/tweaker_tools.py b/etgtools/tweaker_tools.py index 1b63c7179..367476b6e 100644 --- a/etgtools/tweaker_tools.py +++ b/etgtools/tweaker_tools.py @@ -19,8 +19,6 @@ import textwrap -PY3 = sys.version_info[0] == 3 - magicMethods = { 'operator!=' : '__ne__', 'operator==' : '__eq__', @@ -123,12 +121,8 @@ def _processItem(item, names): names = list() filename = 'wx/core.pyi' - if PY3: - with open(filename, 'rt', encoding='utf-8') as f: - text = f.read() - else: - with open(filename, 'r') as f: - text = f.read() + with open(filename, 'rt', encoding='utf-8') as f: + text = f.read() parseTree = ast.parse(text, filename) for item in parseTree.body: _processItem(item, names) diff --git a/packaging/setup.py b/packaging/setup.py index 6df4be608..1a0ab5ad1 100644 --- a/packaging/setup.py +++ b/packaging/setup.py @@ -15,7 +15,7 @@ # folder, so let's accommodate them... #--------------------------------------------------------------------------- -import sys, os, glob +import os, glob # Restructure the content of the tarball so things like pip or easy_install # know how to build stuff. To be compatible with those tools the main source @@ -39,10 +39,7 @@ # Now execute the real setup.py that was copied here in order to do whatever # command was trying to be done before. -if sys.version_info < (3,): - execfile('setup.py') -else: - with open('setup.py', 'r') as f: - source = f.read() - exec(source) +with open('setup.py', 'r') as f: + source = f.read() +exec(source) diff --git a/sphinxtools/inheritance.py b/sphinxtools/inheritance.py index acd7a8035..18704ed39 100644 --- a/sphinxtools/inheritance.py +++ b/sphinxtools/inheritance.py @@ -24,13 +24,9 @@ ENOENT = getattr(errno, 'ENOENT', 0) EPIPE = getattr(errno, 'EPIPE', 0) -if sys.version_info < (3, ): - string_base = basestring -else: - string_base = str -class InheritanceDiagram(object): +class InheritanceDiagram: """ Given a list of classes, determines the set of classes that they inherit from all the way to the root "object", and then is able to generate a @@ -239,7 +235,7 @@ def makeInheritanceDiagram(self, class_summary=None): code = self.generate_dot(class_summary) # graphviz expects UTF-8 by default - if isinstance(code, string_base): + if isinstance(code, str): code = code.encode('utf-8') dot_args = ['dot'] diff --git a/sphinxtools/librarydescription.py b/sphinxtools/librarydescription.py index 56d481344..6fa287066 100644 --- a/sphinxtools/librarydescription.py +++ b/sphinxtools/librarydescription.py @@ -1,25 +1,17 @@ import sys import os import re - -if sys.version_info < (3,): - from StringIO import StringIO -else: - from io import StringIO +from io import StringIO from inspect import getmro, getclasstree, getdoc, getcomments from .utilities import makeSummary, chopDescription, writeSphinxOutput, PickleFile -from .utilities import findControlImages, formatExternalLink, isPython3 +from .utilities import findControlImages, formatExternalLink from .constants import object_types, MODULE_TO_ICON, DOXY_2_REST, SPHINXROOT from . import templates EPYDOC_PATTERN = re.compile(r'\S+{\S+}', re.DOTALL) -if sys.version_info < (3,): - reload(sys) - sys.setdefaultencoding('utf-8') - def make_class_tree(tree): @@ -1016,12 +1008,7 @@ def Write(self, stream, class_name): class Attribute(ChildrenBase): def __init__(self, name, specs, value): - - if isPython3(): - specs = str(specs) - else: - specs = unicode(specs) - + specs = str(specs) start, end = specs.find("'"), specs.rfind("'") specs = specs[start+1:end] diff --git a/sphinxtools/modulehunter.py b/sphinxtools/modulehunter.py index f53ad678e..7626614a2 100644 --- a/sphinxtools/modulehunter.py +++ b/sphinxtools/modulehunter.py @@ -148,10 +148,7 @@ def analyze_params(obj, signature): pvalue = pvalue.strip() if pname in pevals: try: - if isPython3(): - peval = str(pevals[pname]) - else: - peval = unicode(pevals[pname]) + peval = str(pevals[pname]) except UnicodeDecodeError: peval = repr(pevals[pname]) except TypeError: @@ -216,7 +213,7 @@ def inspect_source(method_class, obj, source): def is_classmethod(instancemethod): """ Determine if an instancemethod is a classmethod. """ - # attribute = (isPython3() and ['__self__'] or ['im_self'])[0] + # attribute = (['__self__'] or ['im_self'])[0] # if hasattr(instancemethod, attribute): # return getattr(instancemethod, attribute) is not None # return False @@ -284,20 +281,11 @@ def describe_func(obj, parent_class, module_name): try: code = None if method in [object_types.METHOD, object_types.METHOD_DESCRIPTOR, object_types.INSTANCE_METHOD]: - if isPython3(): - code = obj.__func__.__code__ - else: - code = obj.im_func.func_code + code = obj.__func__.__code__ elif method == object_types.STATIC_METHOD: - if isPython3(): - code = obj.__func__.__code__ - else: - code = obj.im_func.func_code + code = obj.__func__.__code__ else: - if isPython3(): - code = obj.__code__ - else: - code = obj.func_code + code = obj.__code__ except AttributeError: code = None diff --git a/sphinxtools/postprocess.py b/sphinxtools/postprocess.py index e65970258..1b991aa50 100644 --- a/sphinxtools/postprocess.py +++ b/sphinxtools/postprocess.py @@ -25,9 +25,6 @@ from .constants import CONSTANT_INSTANCES, WIDGETS_IMAGES_ROOT, SPHINX_IMAGES_ROOT from .constants import DOCSTRING_KEY -PY2 = sys.version_info[0] == 2 -PY3 = sys.version_info[0] == 3 - # ----------------------------------------------------------------------- # @@ -750,7 +747,7 @@ def removeHeaderImage(text, options): tag = soup.find('div', 'headerimage') if tag: tag.extract() - text = unicode(soup) if PY2 else str(soup) + text = str(soup) return text @@ -762,7 +759,7 @@ def tweakModuleIndex(text): href = tag['href'].split('.html#') if len(href) == 2 and href[0] == href[1]: tag['href'] = href[0] + '.html' - return unicode(soup) if PY2 else str(soup) + return str(soup) def tooltipsOnInheritance(text, class_summary): diff --git a/sphinxtools/utilities.py b/sphinxtools/utilities.py index e218ff902..dee5241d6 100644 --- a/sphinxtools/utilities.py +++ b/sphinxtools/utilities.py @@ -16,14 +16,8 @@ import shutil import re -if sys.version_info < (3,): - import cPickle as pickle - from UserDict import UserDict - string_base = basestring -else: - import pickle - from collections import UserDict - string_base = str +import pickle +from collections import UserDict # Phoenix-specific imports from .templates import TEMPLATE_CONTRIB @@ -444,7 +438,7 @@ def findControlImages(elementOrString): """ from etgtools.tweaker_tools import removeWxPrefix - if isinstance(elementOrString, string_base): + if isinstance(elementOrString, str): class_name = py_class_name = elementOrString.lower() else: element = elementOrString @@ -856,12 +850,6 @@ def formatExternalLink(fullname, inheritance=False): return full_page -def isPython3(): - """ Returns ``True`` if we are using Python 3.x. """ - - return sys.version_info >= (3, ) - - def textfile_open(filename, mode='rt'): """ Simple wrapper around open() that will use codecs.open on Python2 and @@ -869,9 +857,4 @@ def textfile_open(filename, mode='rt'): mode parameter must include the 't' to put the stream into text mode. """ assert 't' in mode - if sys.version_info < (3,): - import codecs - mode = mode.replace('t', '') - return codecs.open(filename, mode, encoding='utf-8') - else: - return open(filename, mode, encoding='utf-8') + return open(filename, mode, encoding='utf-8') diff --git a/wx/lib/activexwrapper.py b/wx/lib/activexwrapper.py index bd1e4c213..d795d80d5 100644 --- a/wx/lib/activexwrapper.py +++ b/wx/lib/activexwrapper.py @@ -24,7 +24,7 @@ if hasattr(sys, "frozen"): import os, win32api dllpath = os.path.join(win32api.GetSystemDirectory(), 'MFC71.DLL') - if sys.version[:3] >= '2.4' and not os.path.exists(dllpath): + if not os.path.exists(dllpath): message = "%s not found" % dllpath else: raise # original error message diff --git a/wx/lib/agw/aui/aui_constants.py b/wx/lib/agw/aui/aui_constants.py index b7add75d7..fc4990102 100644 --- a/wx/lib/agw/aui/aui_constants.py +++ b/wx/lib/agw/aui/aui_constants.py @@ -2594,16 +2594,7 @@ if __name__ == '__main__': # Easy image extraction. import sys - if sys.version_info[0] == 2: - PY2 = True - PY3 = False - elif sys.version_info[0] == 3: - PY2 = False - PY3 = True - if PY2: - answer = int(raw_input('Enter 1 to extract all bitmaps: ')) - elif PY3: - answer = int(input('Enter 1 to extract all bitmaps: ')) + answer = int(input('Enter 1 to extract all bitmaps: ')) if answer == 1: app = wx.App(0) import os @@ -2622,7 +2613,4 @@ except Exception: pass app.MainLoop() - if PY2: - raw_input('Press Enter To Exit.') - elif PY3: - input('Press Enter To Exit.') \ No newline at end of file + input('Press Enter To Exit.') diff --git a/wx/py/sliceshell.py b/wx/py/sliceshell.py index f2d57936e..dcfb918a3 100755 --- a/wx/py/sliceshell.py +++ b/wx/py/sliceshell.py @@ -1008,12 +1008,9 @@ def execStartupScript(self, startupScript): """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/tests/test_introspect.py b/wx/py/tests/test_introspect.py index 9c2f97757..87804e4b7 100644 --- a/wx/py/tests/test_introspect.py +++ b/wx/py/tests/test_introspect.py @@ -8,8 +8,6 @@ import unittest from wx.py import introspect -PY3 = sys.version_info[0] == 3 - """ These unittest methods are preferred: ------------------------------------- @@ -394,21 +392,6 @@ def test_getBaseObject(self): # Class with no init. (Bar, Bar, 0), ] - if not PY3: - values.extend([ - # Byte-compiled code. - (ham.func_code, ham.func_code, 0), - # Class with init. - (Foo, Foo.__init__.im_func, 1), - # Bound method. - (spam.foo, spam.foo.im_func, 1), - # Bound method with self named something else (spam). - (spam.bar, spam.bar.im_func, 1), - # Unbound method. (Do not drop the self argument.) - (eggs, eggs.im_func, 0), - # Callable instance. - (spam, spam.__call__.im_func, 1), - ]) for object, baseObject, dropSelf in values: result = introspect.getBaseObject(object) self.assertEqual(result, (baseObject, dropSelf)) @@ -674,16 +657,6 @@ def setUp(self): # BrokenStr instance. brokenStr, ] - if not PY3: - self.items.extend([ - long(123), - unicode(""), - xrange(0), - # Byte-compiled code. - ham.func_code, - # Buffer. - buffer(''), - ]) def tearDown(self): self.items = None @@ -829,34 +802,11 @@ def __init__(self, c, d=4): class GetConstructorTestCase(unittest.TestCase): - @unittest.skipIf(PY3, "Python2 specific test") - def test_getConstructor(self): - args = ('self', 'a', 'b', 'args', 'kwargs') - varnames = introspect.getConstructor(O).func_code.co_varnames - self.assertEqual(varnames, args) - varnames = introspect.getConstructor(P).func_code.co_varnames - self.assertEqual(varnames, args) - args = ('self', 'c', 'd') - varnames = introspect.getConstructor(Q).func_code.co_varnames - self.assertEqual(varnames, args) - def test_getConstructor_None(self): values = (N, 1, 'spam', {}, [], (), dir) for value in values: self.assertEqual(introspect.getConstructor(N), None) - @unittest.skipIf(PY3, "Python2 specific test") - def test_getConstructor_MultipleInheritance(self): - # Test old style inheritance rules. - args = ('self', 'a') - varnames = introspect.getConstructor(D1).func_code.co_varnames - self.assertEqual(varnames, args) - if 'object' in __builtins__: - # Test new style inheritance rules as well. - args = ('self', 'b') - varnames = introspect.getConstructor(D2).func_code.co_varnames - self.assertEqual(varnames, args) - if __name__ == '__main__': unittest.main() diff --git a/wx/svg/_nanosvg.pyx b/wx/svg/_nanosvg.pyx index d1cae1aa9..3dbb1adbf 100644 --- a/wx/svg/_nanosvg.pyx +++ b/wx/svg/_nanosvg.pyx @@ -46,8 +46,6 @@ from cpython.buffer cimport ( Py_buffer, PyObject_CheckBuffer, PyObject_GetBuffer, PyBUF_SIMPLE, PyBuffer_Release) -PY2 = sys.version_info[0] == 2 - #---------------------------------------------------------------------------- # Replicate the C enums and values for Python, dropping the leading 'N' diff --git a/wx/tools/img2py.py b/wx/tools/img2py.py index 258e72c72..f848b4469 100644 --- a/wx/tools/img2py.py +++ b/wx/tools/img2py.py @@ -198,10 +198,7 @@ def img2py(image_file, python_file, while data: part = data[:72] data = data[72:] - if sys.version > '3': - output = ' %s' % part - else: - output = ' "%s"' % part + output = ' %s' % part if not data: output += ")" lines.append(output) From 22820375ca6d4a6b4db7fca588ab88079566238c Mon Sep 17 00:00:00 2001 From: Alexandre Detiste Date: Fri, 22 Mar 2024 08:15:00 +0100 Subject: [PATCH 4/4] finish removing six --- demo/KeyEvents.py | 7 +++---- demo/Main.py | 11 ++++++----- demo/Threads.py | 2 +- requirements/install.txt | 2 -- wx/lib/agw/zoombar.py | 4 +--- wx/lib/intctrl.py | 5 ++--- wx/svg/__init__.py | 2 +- wx/tools/pywxrc.py | 4 +++- 8 files changed, 17 insertions(+), 20 deletions(-) diff --git a/demo/KeyEvents.py b/demo/KeyEvents.py index b6239675b..f0f48851d 100644 --- a/demo/KeyEvents.py +++ b/demo/KeyEvents.py @@ -2,7 +2,6 @@ import wx import wx.lib.mixins.listctrl as listmix -from six import unichr #---------------------------------------------------------------------- @@ -265,15 +264,15 @@ def LogKeyEvent(self, evType, evt): if keycode == 0: keyname = "NUL" elif keycode < 27: - keyname = u"Ctrl-%s" % unichr(ord('A') + keycode-1) + keyname = u"Ctrl-%s" % chr(ord('A') + keycode-1) else: - keyname = u"\"%s\"" % unichr(keycode) + keyname = u"\"%s\"" % chr(keycode) else: keyname = u"(%s)" % keycode UniChr = '' if "unicode" in wx.PlatformInfo: - UniChr = "\"" + unichr(evt.GetUnicodeKey()) + "\"" + UniChr = "\"" + chr(evt.GetUnicodeKey()) + "\"" modifiers = "" for mod, ch in [(evt.ControlDown(), 'C'), diff --git a/demo/Main.py b/demo/Main.py index 0c5ea6eea..0264de0a0 100644 --- a/demo/Main.py +++ b/demo/Main.py @@ -52,8 +52,11 @@ # Last updated: Andrea Gavana, 20 Oct 2008, 18.00 GMT import sys, os, time, traceback +import pickle import re import shutil +import urllib.error +import urllib.request from io import BytesIO from threading import Thread @@ -67,8 +70,6 @@ from wx.adv import SplashScreen as SplashScreen import wx.lib.mixins.inspection -from six.moves import cPickle -from six.moves import urllib import version @@ -1636,7 +1637,7 @@ def ReadConfigurationFile(self): with open(pickledFile, "rb") as fid: try: - self.pickledData = cPickle.load(fid) + self.pickledData = pickle.load(fid) except: self.pickledData = {} @@ -1677,7 +1678,7 @@ def BuildMenuBar(self): item.Check(self.allowDocs) self.Bind(wx.EVT_MENU, self.OnAllowDownload, item) - item = wx.MenuItem(menu, -1, 'Delete saved docs', 'Deletes the cPickle file where docs are stored') + item = wx.MenuItem(menu, -1, 'Delete saved docs', 'Deletes the pickle file where docs are stored') item.SetBitmap(images.catalog['deletedocs'].GetBitmap()) menu.Append(item) self.Bind(wx.EVT_MENU, self.OnDeleteDocs, item) @@ -2486,7 +2487,7 @@ def OnCloseWindow(self, event): MakeDocDirs() pickledFile = GetDocFile() with open(pickledFile, "wb") as fid: - cPickle.dump(self.pickledData, fid, cPickle.HIGHEST_PROTOCOL) + pickle.dump(self.pickledData, fid, pickle.HIGHEST_PROTOCOL) self.Destroy() diff --git a/demo/Threads.py b/demo/Threads.py index 9dff29705..fca037d99 100644 --- a/demo/Threads.py +++ b/demo/Threads.py @@ -1,6 +1,6 @@ import random import time -from six.moves import _thread +import _thread import wx import wx.lib.newevent diff --git a/requirements/install.txt b/requirements/install.txt index 2061eda20..e62c2e134 100644 --- a/requirements/install.txt +++ b/requirements/install.txt @@ -1,5 +1,3 @@ # Runtime dependencies needed when using wxPython Phoenix -numpy < 1.17 ; python_version <= '2.7' numpy ; python_version >= '3.0' and python_version < '3.12' # pillow < 3.0 -six diff --git a/wx/lib/agw/zoombar.py b/wx/lib/agw/zoombar.py index 8c2afd058..144d04292 100644 --- a/wx/lib/agw/zoombar.py +++ b/wx/lib/agw/zoombar.py @@ -133,8 +133,6 @@ def __init__(self, parent): import wx import sys -import six - from wx.lib.embeddedimage import PyEmbeddedImage zoombackgrey = PyEmbeddedImage( @@ -375,7 +373,7 @@ def __init__(self, parent, bitmap, disabledBmp=wx.NullBitmap, label=""): self._oldHeight = 0 self._vCenter = 0 self._hCenter = 0 - self._oldInc = -six.MAXSIZE + self._oldInc = -sys.MAXSIZE self._isSeparator = False self._enabled = True diff --git a/wx/lib/intctrl.py b/wx/lib/intctrl.py index f1740cc1a..5cb9123fc 100644 --- a/wx/lib/intctrl.py +++ b/wx/lib/intctrl.py @@ -41,12 +41,11 @@ import types import wx -import six #---------------------------------------------------------------------------- -MAXSIZE = six.MAXSIZE # (constants should be in upper case) -MINSIZE = -six.MAXSIZE-1 +MAXSIZE = sys.maxsize # (constants should be in upper case) +MINSIZE = -sys.MAXSIZE-1 LONGTYPE = int #---------------------------------------------------------------------------- diff --git a/wx/svg/__init__.py b/wx/svg/__init__.py index 9f611110b..ff196cb10 100644 --- a/wx/svg/__init__.py +++ b/wx/svg/__init__.py @@ -80,9 +80,9 @@ def OnPaint(self, event): bmp = img.ConvertToScaledBitmap(wx.Size(24,24), self) """ +from itertools import zip_longest import wx -from six.moves import zip_longest from ._nanosvg import * diff --git a/wx/tools/pywxrc.py b/wx/tools/pywxrc.py index 2dd16a402..3aafd9624 100644 --- a/wx/tools/pywxrc.py +++ b/wx/tools/pywxrc.py @@ -33,7 +33,9 @@ import sys, os, getopt, glob, re import xml.dom.minidom as minidom -from six import byte2int + +import operator +byte2int = operator.itemgetter(0) #----------------------------------------------------------------------