From 11bafeba4426c04a997303dad0e255981a4f6767 Mon Sep 17 00:00:00 2001 From: Shlomi Fish Date: Sat, 1 Sep 2018 18:40:50 +0300 Subject: [PATCH] use six.py. --- pysollib/configobj/configobj.py | 27 +++++++++++++-------------- pysollib/configobj/validate.py | 6 ++---- pysollib/customgame.py | 7 ++----- pysollib/game.py | 11 ++++------- pysollib/gamedb.py | 14 +++++--------- pysollib/hint.py | 13 ++++++------- pysollib/mfxutil.py | 5 ++--- pysollib/mygettext.py | 16 +++++++--------- pysollib/options.py | 6 ++---- pysollib/pysolgtk/statusbar.py | 9 +++------ pysollib/pysolgtk/tkhtml.py | 6 ++---- pysollib/resource.py | 7 ++----- pysollib/tile/selecttile.py | 10 +++------- pysollib/tile/statusbar.py | 6 ++---- pysollib/tile/tkwidget.py | 22 ++++++++-------------- pysollib/tile/ttk.py | 22 ++++++++++------------ pysollib/tile/wizarddialog.py | 9 +++------ pysollib/tk/selecttile.py | 10 +++------- pysollib/tk/statusbar.py | 7 ++----- pysollib/tk/tkwidget.py | 9 +++------ pysollib/tk/wizarddialog.py | 10 +++------- pysollib/wizardutil.py | 12 ++++-------- 22 files changed, 91 insertions(+), 153 deletions(-) diff --git a/pysollib/configobj/configobj.py b/pysollib/configobj/configobj.py index 482562cb..6cb5b6d6 100644 --- a/pysollib/configobj/configobj.py +++ b/pysollib/configobj/configobj.py @@ -20,6 +20,7 @@ import sys import os import re +import six from six import string_types from warnings import warn @@ -27,9 +28,6 @@ INTP_VER = sys.version_info[:2] if INTP_VER < (2, 2): raise RuntimeError("Python v.2.2 or later needed") -if sys.version_info > (3,): - unicode = str - compiler = None try: import compiler @@ -860,7 +858,8 @@ class Section(dict): def decode(self, encoding): """ - Decode all strings and values to unicode, using the specified encoding. + Decode all strings and values to unicode, using the specified + encoding. Works with subsections and list values. @@ -871,12 +870,12 @@ class Section(dict): >>> m.decode('ascii') >>> def testuni(val): ... for entry in val: - ... if not isinstance(entry, unicode): + ... if not isinstance(entry, six.text_type): ... print >> sys.stderr, type(entry) ... raise AssertionError, 'decode failed.' ... if isinstance(val[entry], dict): ... testuni(val[entry]) - ... elif not isinstance(val[entry], unicode): + ... elif not isinstance(val[entry], six.text_type): ... raise AssertionError, 'decode failed.' >>> testuni(m) >>> m.encode('ascii') @@ -904,7 +903,7 @@ class Section(dict): def encode(self, encoding): """ - Encode all strings and values from unicode, + Encode all strings and values from six.text_type, using the specified encoding. Works with subsections and list values. @@ -1174,7 +1173,7 @@ class ConfigObj(Section): self.filename = infile if os.path.isfile(infile): if sys.version_info > (3,): - infile = unicode(open(infile).read()) or [] + infile = six.text_type(open(infile).read()) or [] else: infile = open(infile).read() or [] elif self.file_error: @@ -1275,7 +1274,7 @@ class ConfigObj(Section): If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to - unicode. + six.text_type. NOTE: This method must not be called with an empty ``infile``. @@ -1376,25 +1375,25 @@ class ConfigObj(Section): def _decode(self, infile, encoding): """ - Decode infile to unicode. Using the specified encoding. + Decode infile to six.text_type. Using the specified encoding. if is a string, it also needs converting to a list. """ if isinstance(infile, string_types): - # can't be unicode + # can't be six.text_type # NOTE: Could raise a ``UnicodeDecodeError`` return infile.decode(encoding).splitlines(True) for i, line in enumerate(infile): - if not isinstance(line, unicode): + if not isinstance(line, six.text_type): # NOTE: The isinstance test here handles mixed - # lists of unicode/string + # lists of six.text_type/string # NOTE: But the decode will break on any non-string values # NOTE: Or could raise a ``UnicodeDecodeError`` infile[i] = line.decode(encoding) return infile def _decode_element(self, line): - """Decode element to unicode if necessary.""" + """Decode element to six.text_type if necessary.""" if not self.encoding: return line if isinstance(line, str) and self.default_encoding: diff --git a/pysollib/configobj/validate.py b/pysollib/configobj/validate.py index 2b9e00fa..dea2a39f 100644 --- a/pysollib/configobj/validate.py +++ b/pysollib/configobj/validate.py @@ -125,6 +125,7 @@ """ import sys +import six import re __docformat__ = "restructuredtext en" @@ -137,10 +138,7 @@ INTP_VER = sys.version_info[:2] if INTP_VER < (2, 2): raise RuntimeError("Python v.2.2 or later needed") -if sys.version_info > (3,): - unicode = str - -StringTypes = (str, unicode) +StringTypes = six.string_types _list_arg = re.compile(r''' diff --git a/pysollib/customgame.py b/pysollib/customgame.py index bba9bf9c..0f5c3df7 100644 --- a/pysollib/customgame.py +++ b/pysollib/customgame.py @@ -21,7 +21,7 @@ # # ---------------------------------------------------------------------------## -import sys +import six from pysollib.gamedb import registerGame, GameInfo, GI from pysollib.util import ACE, ANY_RANK, ANY_SUIT, \ KING, \ @@ -68,14 +68,11 @@ from pysollib.wizardutil import WizardWidgets # * # ************************************************************************ -if sys.version_info > (3,): - basestring = str - def get_settings(ss): s = {} for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): continue if w.var_name in ss: v = ss[w.var_name] diff --git a/pysollib/game.py b/pysollib/game.py index 813d03ec..a7b423e3 100644 --- a/pysollib/game.py +++ b/pysollib/game.py @@ -23,10 +23,10 @@ # imports -import sys import time import math import traceback +import six from pysollib.mygettext import _ from gettext import ungettext @@ -66,9 +66,6 @@ if True: # This prevents from travis 'error' E402. from pysollib.hint import DefaultHint from pysollib.help import help_about -if sys.version_info > (3,): - basestring = str - PLAY_TIME_TIMEOUT = 200 # ************************************************************************ @@ -1039,7 +1036,7 @@ class Game(object): # self.top.wm_title("%s - %s" # % (TITLE, self.getTitleName())) continue - if isinstance(v, basestring): + if isinstance(v, six.string_types): if sb: sb.updateText(gamenumber=v) # self.top.wm_title("%s - %s %s" % (TITLE, @@ -1081,7 +1078,7 @@ class Game(object): if tb: tb.updateText(player=_("Player\n")) continue - if isinstance(v, basestring): + if isinstance(v, six.string_types): if tb: # if self.app.opt.toolbar_size: if self.app.toolbar.getSize(): @@ -1103,7 +1100,7 @@ class Game(object): if v is None: if sb: sb.updateText(time='') - if isinstance(v, basestring): + if isinstance(v, six.string_types): if sb: sb.updateText(time=v) continue diff --git a/pysollib/gamedb.py b/pysollib/gamedb.py index 278aa4e9..2db4de12 100644 --- a/pysollib/gamedb.py +++ b/pysollib/gamedb.py @@ -23,7 +23,7 @@ # imports -import sys +import six import imp # PySol imports @@ -33,10 +33,6 @@ import pysollib.settings from pysollib.mygettext import _, n_ -if sys.version_info > (3,): - basestring = str - unicode = str - # ************************************************************************ # * constants # ************************************************************************ @@ -454,13 +450,13 @@ class GameInfo(Struct): ): # def to_unicode(s): - if isinstance(s, unicode): + if isinstance(s, six.text_type): return s try: - s = unicode(s, 'utf-8') + s = six.text_type(s, 'utf-8') except UnicodeDecodeError as err: print_err(err) - s = unicode(s, 'utf-8', 'ignore') + s = six.text_type(s, 'utf-8', 'ignore') return s ncards = decks * (len(suits) * len(ranks) + len(trumps)) game_flags = game_type & ~1023 @@ -475,7 +471,7 @@ class GameInfo(Struct): short_name = to_unicode(short_name) if pysollib.settings.TRANSLATE_GAME_NAMES: short_name = _(short_name) - if isinstance(altnames, basestring): + if isinstance(altnames, six.string_types): altnames = (altnames,) altnames = [to_unicode(n) for n in altnames] if pysollib.settings.TRANSLATE_GAME_NAMES: diff --git a/pysollib/hint.py b/pysollib/hint.py index 7824d6e4..c4c5c89d 100644 --- a/pysollib/hint.py +++ b/pysollib/hint.py @@ -28,6 +28,7 @@ import time import subprocess import re import sys +import six from io import BytesIO # PySol imports @@ -37,8 +38,6 @@ from pysollib.mfxutil import destruct from pysollib.util import KING FCS_VERSION = None -if sys.version_info > (3,): - unicode = str # ************************************************************************ # * HintInterface is an abstract class that defines the public @@ -1000,7 +999,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): global FCS_VERSION if FCS_VERSION is None: pout, _ = self.run_solver(FCS_COMMAND + ' --version', '') - s = unicode(pout.read(), encoding='utf-8') + s = six.text_type(pout.read(), encoding='utf-8') m = re.search(r'version ([0-9]+)\.([0-9]+)\.([0-9]+)', s) if m: FCS_VERSION = (int(m.group(1)), int(m.group(2)), @@ -1064,7 +1063,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): states = 0 for sbytes in pout: - s = unicode(sbytes, encoding='utf-8') + s = six.text_type(sbytes, encoding='utf-8') if DEBUG >= 5: print(s) @@ -1085,7 +1084,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): hints = [] for sbytes in pout: - s = unicode(sbytes, encoding='utf-8') + s = six.text_type(sbytes, encoding='utf-8') if DEBUG: print(s) if self._determineIfSolverState(s): @@ -1219,7 +1218,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): states = 0 for sbytes in pout: - s = unicode(sbytes, encoding='utf-8') + s = six.text_type(sbytes, encoding='utf-8') if DEBUG >= 5: print(s) @@ -1233,7 +1232,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): hints = [] for sbytes in pout: - s = unicode(sbytes, encoding='utf-8') + s = six.text_type(sbytes, encoding='utf-8') if DEBUG: print(s) m = re.match('Total number of states checked is (\d+)\.', s) diff --git a/pysollib/mfxutil.py b/pysollib/mfxutil.py index ce90c4fc..ee8b9efd 100644 --- a/pysollib/mfxutil.py +++ b/pysollib/mfxutil.py @@ -24,6 +24,7 @@ # imports import re import sys +import six import os import time import locale @@ -54,8 +55,6 @@ USE_PIL = False if TOOLKIT == 'tk' and Image and Image.VERSION >= '1.1.7': USE_PIL = True -if sys.version_info > (3,): - unicode = str # debug # Image = None # USE_PIL = False @@ -158,7 +157,7 @@ if os.name == "posix": def win32_getusername(): user = os.environ.get('USERNAME', '').strip() try: - user = unicode(user, locale.getpreferredencoding()) + user = six.text_type(user, locale.getpreferredencoding()) except Exception: user = '' return user diff --git a/pysollib/mygettext.py b/pysollib/mygettext.py index 296f948e..43080ee1 100644 --- a/pysollib/mygettext.py +++ b/pysollib/mygettext.py @@ -1,8 +1,6 @@ import gettext import sys - -if sys.version_info > (3,): - unicode = str +import six def n_(x): @@ -12,8 +10,8 @@ def n_(x): def fix_gettext(): def ugettext(message): # unicoded gettext - if not isinstance(message, unicode): - message = unicode(message, 'utf-8') + if not isinstance(message, six.text_type): + message = six.text_type(message, 'utf-8') domain = gettext._current_domain try: t = gettext.translation(domain, @@ -29,10 +27,10 @@ def fix_gettext(): def ungettext(msgid1, msgid2, n): # unicoded ngettext - if not isinstance(msgid1, unicode): - msgid1 = unicode(msgid1, 'utf-8') - if not isinstance(msgid2, unicode): - msgid2 = unicode(msgid2, 'utf-8') + if not isinstance(msgid1, six.text_type): + msgid1 = six.text_type(msgid1, 'utf-8') + if not isinstance(msgid2, six.text_type): + msgid2 = six.text_type(msgid2, 'utf-8') domain = gettext._current_domain try: t = gettext.translation(domain, diff --git a/pysollib/options.py b/pysollib/options.py index fa15f49c..87ca68fc 100644 --- a/pysollib/options.py +++ b/pysollib/options.py @@ -23,6 +23,7 @@ # imports import sys +import six import os import traceback @@ -37,9 +38,6 @@ from pysollib.pysoltk import TOOLBAR_BUTTONS, TOOLKIT from pysollib.mygettext import _ -if sys.version_info > (3,): - unicode = str - # ************************************************************************ # * Options # ************************************************************************ @@ -516,7 +514,7 @@ class Options: val = getattr(self, key) if isinstance(val, str): if sys.version_info < (3,): - val = unicode(val, 'utf-8') + val = six.text_type(val, 'utf-8') config['general'][key] = val config['general']['recent_gameid'] = self.recent_gameid diff --git a/pysollib/pysolgtk/statusbar.py b/pysollib/pysolgtk/statusbar.py index f41468d6..4c8e0150 100644 --- a/pysollib/pysolgtk/statusbar.py +++ b/pysollib/pysolgtk/statusbar.py @@ -23,15 +23,12 @@ # imports -import sys import gtk +import six # PySol imports from pysollib.mygettext import _ - -if sys.version_info > (3,): - unicode = str # ************************************************************************ # * # ************************************************************************ @@ -69,7 +66,7 @@ class BasicStatusbar: for k, v in kw.items(): label = getattr(self, k + "_label") label.pop(0) - label.push(0, unicode(v)) + label.push(0, six.text_type(v)) def config(self, name, show): # FIXME @@ -79,7 +76,7 @@ class BasicStatusbar: label = getattr(self, name + "_label") # FIXME kw['fg'] label.pop(0) - label.push(0, unicode(kw['text'])) + label.push(0, six.text_type(kw['text'])) def show(self, show=True, resize=False): if show: diff --git a/pysollib/pysolgtk/tkhtml.py b/pysollib/pysolgtk/tkhtml.py index 8da3b134..a167f80f 100644 --- a/pysollib/pysolgtk/tkhtml.py +++ b/pysollib/pysolgtk/tkhtml.py @@ -24,6 +24,7 @@ # imports import os import sys +import six import htmllib import formatter import traceback @@ -47,9 +48,6 @@ if __name__ == '__main__': import gettext gettext.install('pysol', d, unicode=True) -if sys.version_info > (3,): - unicode = str - REMOTE_PROTOCOLS = ('ftp:', 'gopher:', 'http:', 'mailto:', 'news:', 'telnet:') @@ -72,7 +70,7 @@ class tkHTMLWriter(formatter.NullWriter): self.indent = '' def write(self, data): - data = unicode(data) + data = six.text_type(data) self.text.insert(self.text.get_end_iter(), data, len(data)) def anchor_bgn(self, href, name, type): diff --git a/pysollib/resource.py b/pysollib/resource.py index e139bd1a..a67168d3 100644 --- a/pysollib/resource.py +++ b/pysollib/resource.py @@ -24,9 +24,9 @@ # imports import os -import sys import glob import traceback +import six # PySol imports from pysollib.mfxutil import Struct, KwStruct @@ -38,9 +38,6 @@ from pysollib.mygettext import _ # * Abstract # ************************************************************************ -if sys.version_info > (3,): - basestring = str - class Resource(Struct): def __init__(self, **kw): @@ -386,7 +383,7 @@ class Cardset(Resource): def updateCardback(self, backname=None, backindex=None): # update default back - if isinstance(backname, basestring): + if isinstance(backname, six.string_types): if backname in self.backnames: backindex = self.backnames.index(backname) if isinstance(backindex, int): diff --git a/pysollib/tile/selecttile.py b/pysollib/tile/selecttile.py index e5fb9815..5480eb6f 100644 --- a/pysollib/tile/selecttile.py +++ b/pysollib/tile/selecttile.py @@ -23,7 +23,7 @@ # imports -import sys +import six from six.moves import tkinter from six.moves import tkinter_colorchooser from . import ttk @@ -39,10 +39,6 @@ from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode from .selecttree import SelectDialogTreeCanvas -if sys.version_info > (3,): - basestring = str - - # ************************************************************************ # * Nodes # ************************************************************************ @@ -169,7 +165,7 @@ class SelectTileDialogWithPreview(MfxDialog): def mDone(self, button): if button == 0: # "OK" or double click - if isinstance(self.tree.selection_key, basestring): + if isinstance(self.tree.selection_key, six.string_types): self.key = str(self.tree.selection_key) else: self.key = self.tree.selection_key @@ -197,7 +193,7 @@ class SelectTileDialogWithPreview(MfxDialog): return canvas = self.preview.canvas canvas.deleteAllItems() - if isinstance(key, basestring): + if isinstance(key, six.string_types): # solid color canvas.config(bg=key) canvas.setTile(None) diff --git a/pysollib/tile/statusbar.py b/pysollib/tile/statusbar.py index d3278886..c40616e6 100644 --- a/pysollib/tile/statusbar.py +++ b/pysollib/tile/statusbar.py @@ -24,6 +24,7 @@ # imports import os import sys +import six from six.moves import tkinter from . import ttk @@ -39,9 +40,6 @@ if __name__ == '__main__': import gettext gettext.install('pysol', d, unicode=True) -if sys.version_info > (3,): - unicode = str - # ************************************************************************ # * # ************************************************************************ @@ -99,7 +97,7 @@ class MfxStatusbar: def updateText(self, **kw): for k, v in kw.items(): label = getattr(self, k + '_label') - text = unicode(v) + text = six.text_type(v) width = label['width'] if width and len(text) > width: label['width'] = len(text) diff --git a/pysollib/tile/tkwidget.py b/pysollib/tile/tkwidget.py index 9fff8183..f8689141 100644 --- a/pysollib/tile/tkwidget.py +++ b/pysollib/tile/tkwidget.py @@ -22,7 +22,6 @@ # --------------------------------------------------------------------------- # imports -import sys import os import time import locale @@ -30,6 +29,7 @@ from six.moves import tkinter from . import ttk from six.moves import tkinter_font from six import PY2 +import six import traceback # PySol imports @@ -43,9 +43,6 @@ from pysollib.ui.tktile.tkutil import bind, unbind_destroy from pysollib.ui.tktile.tkutil import makeToplevel, setTransient from pysollib.ui.tktile.tkcanvas import MfxCanvas -if sys.version_info > (3,): - unicode = str - # ************************************************************************ # * abstract base class for the dialogs in this module # ************************************************************************ @@ -125,9 +122,9 @@ class MfxDialog: # ex. _ToplevelDialog key = event.char try: if os.name == 'nt': - key = unicode(key, locale.getpreferredencoding()) + key = six.text_type(key, locale.getpreferredencoding()) else: - key = unicode(key, 'utf-8') + key = six.text_type(key, 'utf-8') except Exception: pass else: @@ -294,7 +291,7 @@ class MfxExceptionDialog(MfxMessageDialog): else: t = str(ex) if PY2: - t = unicode(t, errors='replace') + t = six.text_type(t, errors='replace') kw.text = text + t MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) @@ -318,13 +315,10 @@ class PysolAboutDialog(MfxMessageDialog): width=kw.width) msg.pack(fill='both', expand=True) - if sys.version_info >= (2, 4): - # font_name = msg.lookup('TLabel', 'font') - font_name = 'TkDefaultFont' - font = tkinter_font.Font(parent, name=font_name, exists=True) - font = font.copy() - else: - font = tkinter_font.Font(parent, app.getFont('default')) + # font_name = msg.lookup('TLabel', 'font') + font_name = 'TkDefaultFont' + font = tkinter_font.Font(parent, name=font_name, exists=True) + font = font.copy() font.configure(underline=True) url_label = ttk.Label(frame, text=kw.url, font=font, foreground='blue', cursor='hand2') diff --git a/pysollib/tile/ttk.py b/pysollib/tile/ttk.py index 3f67720c..e53e3806 100644 --- a/pysollib/tile/ttk.py +++ b/pysollib/tile/ttk.py @@ -16,18 +16,14 @@ __version__ = "0.3" __author__ = "Guilherme Polo " -import sys from six.moves import tkinter +import six _flatten = tkinter._flatten # Verify if Tk is new enough to not need Tile checking _REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False -if sys.version_info > (3,): - basestring = str - unicode = str - def _loadttk(loadtk): # This extends the default tkinter.Tk._loadtk method so we can be @@ -68,8 +64,8 @@ def _format_optdict(optdict, script=False, ignore=None): if isinstance(value, (list, tuple)): v = [] for val in value: - if isinstance(val, basestring): - v.append(unicode(val) if val else '{}') + if isinstance(val, six.string_types): + v.append(six.text_type(val) if val else '{}') else: v.append(str(val)) @@ -226,11 +222,12 @@ def _script_from_settings(settings): # will format specific keys according to Tcl code if opts.get('configure'): # format 'configure' s = ' '.join( - map(unicode, _format_optdict(opts['configure'], True))) + map(six.text_type, _format_optdict(opts['configure'], True))) script.append("ttk::style configure %s %s;" % (name, s)) if opts.get('map'): # format 'map' - s = ' '.join(map(unicode, _format_mapdict(opts['map'], True))) + s = ' '.join(map(six.text_type, + _format_mapdict(opts['map'], True))) script.append("ttk::style map %s %s;" % (name, s)) if 'layout' in opts: # format 'layout' which may be empty @@ -338,7 +335,7 @@ def _val_or_dict(options, func, *args): def _convert_stringval(value): """Converts a value to, hopefully, a more appropriate Python object.""" - value = unicode(value) + value = six.text_type(value) try: value = int(value) except (ValueError, TypeError): @@ -351,7 +348,8 @@ def tclobjs_to_py(adict): """Returns adict with its values converted from Tcl objects to Python objects.""" for opt, val in adict.items(): - if val and hasattr(val, '__len__') and not isinstance(val, basestring): + if val and hasattr(val, '__len__') and \ + not isinstance(val, six.string_types): if getattr(val[0], 'typename', None) == 'StateSpec': val = _list_from_statespec(val) else: @@ -1234,7 +1232,7 @@ class Treeview(Widget): To configure the tree column heading, call this with column = "#0" """ cmd = kw.get('command') - if cmd and not isinstance(cmd, basestring): + if cmd and not isinstance(cmd, six.string_types): # callback not registered yet, do it now kw['command'] = self.master.register(cmd, self._substitute) diff --git a/pysollib/tile/wizarddialog.py b/pysollib/tile/wizarddialog.py index 0afce180..f5b03107 100644 --- a/pysollib/tile/wizarddialog.py +++ b/pysollib/tile/wizarddialog.py @@ -22,8 +22,8 @@ # --------------------------------------------------------------------------- # imports -import sys +import six from six.moves import tkinter from . import ttk @@ -37,9 +37,6 @@ from pysollib.wizardpresets import presets from .tkwidget import MfxDialog from .tkwidget import PysolScale, PysolCombo -if sys.version_info > (3,): - basestring = str - # ************************************************************************ # * # ************************************************************************ @@ -60,7 +57,7 @@ class WizardDialog(MfxDialog): notebook.pack(expand=True, fill='both') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): frame = ttk.Frame(notebook) notebook.add(frame, text=w, sticky='nsew', padding=5) frame.columnconfigure(1, weight=1) @@ -139,7 +136,7 @@ class WizardDialog(MfxDialog): n = w.translation_map[n] p = presets[n] for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): continue if w.var_name in p: v = p[w.var_name] diff --git a/pysollib/tk/selecttile.py b/pysollib/tk/selecttile.py index ba767c1e..ceef400c 100644 --- a/pysollib/tk/selecttile.py +++ b/pysollib/tk/selecttile.py @@ -23,7 +23,7 @@ # imports -import sys +import six from six.moves import tkinter, tkinter_colorchooser # PySol imports @@ -37,10 +37,6 @@ from .selecttree import SelectDialogTreeCanvas from pysollib.ui.tktile.selecttree import SelectDialogTreeData -if sys.version_info > (3,): - basestring = str - - # ************************************************************************ # * Nodes # ************************************************************************ @@ -167,7 +163,7 @@ class SelectTileDialogWithPreview(MfxDialog): def mDone(self, button): if button == 0: # "OK" or double click - if isinstance(self.tree.selection_key, basestring): + if isinstance(self.tree.selection_key, six.string_types): self.key = str(self.tree.selection_key) else: self.key = self.tree.selection_key @@ -196,7 +192,7 @@ class SelectTileDialogWithPreview(MfxDialog): return canvas = self.preview.canvas canvas.deleteAllItems() - if isinstance(key, basestring): + if isinstance(key, six.string_types): # solid color canvas.config(bg=key) canvas.setTile(None) diff --git a/pysollib/tk/statusbar.py b/pysollib/tk/statusbar.py index a9abe9c2..997a40bd 100644 --- a/pysollib/tk/statusbar.py +++ b/pysollib/tk/statusbar.py @@ -24,15 +24,12 @@ # imports import os import sys +import six from six.moves import tkinter from pysollib.mygettext import _ from .tkwidget import MfxTooltip from pysollib.settings import WIN_SYSTEM -if sys.version_info > (3,): - unicode = str - - if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir)) sys.path.append(d) @@ -97,7 +94,7 @@ class MfxStatusbar: def updateText(self, **kw): for k, v in kw.items(): label = getattr(self, k + '_label') - text = unicode(v) + text = six.text_type(v) width = label['width'] if width and len(text) > width: label['width'] = len(text) diff --git a/pysollib/tk/tkwidget.py b/pysollib/tk/tkwidget.py index aedfd0a6..45b6f573 100644 --- a/pysollib/tk/tkwidget.py +++ b/pysollib/tk/tkwidget.py @@ -22,7 +22,7 @@ # --------------------------------------------------------------------------- # imports -import sys +import six import time from six.moves import tkinter from six.moves import tkinter_font @@ -39,9 +39,6 @@ from pysollib.ui.tktile.tkutil import bind, unbind_destroy from pysollib.ui.tktile.tkutil import makeToplevel, setTransient from pysollib.ui.tktile.tkcanvas import MfxCanvas -if sys.version_info > (3,): - unicode = str - # ************************************************************************ # * abstract base class for the dialogs in this module # ************************************************************************ @@ -136,7 +133,7 @@ class MfxDialog: # ex. _ToplevelDialog def altKeyEvent(self, event): key = event.char - key = unicode(key, 'utf-8') + key = six.text_type(key, 'utf-8') key = key.lower() button = self.accel_keys.get(key) if button is not None: @@ -291,7 +288,7 @@ class MfxExceptionDialog(MfxMessageDialog): (ex.errno, ex.strerror, repr(ex.filename)) else: t = str(ex) - kw.text = text + unicode(t, errors='replace') + kw.text = text + six.text_type(t, errors='replace') MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) diff --git a/pysollib/tk/wizarddialog.py b/pysollib/tk/wizarddialog.py index 71d92050..ff412e6d 100644 --- a/pysollib/tk/wizarddialog.py +++ b/pysollib/tk/wizarddialog.py @@ -22,7 +22,7 @@ # ---------------------------------------------------------------------------## # imports -import sys +import six from six.moves import tkinter from .tabpage import TabPageSet @@ -36,10 +36,6 @@ from pysollib.wizardpresets import presets from .tkwidget import MfxDialog -if sys.version_info > (3,): - basestring = str - - # ************************************************************************ # * # ************************************************************************ @@ -59,7 +55,7 @@ class WizardDialog(MfxDialog): notebook.pack(expand=True, fill='both') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): notebook.AddPage(w) frame = tkinter.Frame(notebook.pages[w]['page']) frame.pack(expand=True, fill='both', padx=2, pady=4) @@ -128,7 +124,7 @@ class WizardDialog(MfxDialog): n = w.translation_map[v] p = presets[n] for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): continue if w.var_name in p: v = p[w.var_name] diff --git a/pysollib/wizardutil.py b/pysollib/wizardutil.py index 2e12c318..991d7308 100644 --- a/pysollib/wizardutil.py +++ b/pysollib/wizardutil.py @@ -21,8 +21,8 @@ # # --------------------------------------------------------------------------- -import sys import os +import six from pysollib.gamedb import GI, loadGame from pysollib.util import ACE, ANY_RANK, KING, NO_RANK, UNLIMITED_MOVES @@ -60,10 +60,6 @@ from pysollib.wizardpresets import presets from pysollib.mygettext import _, n_ -if sys.version_info > (3,): - basestring = str - unicode = str - # ************************************************************************ # * # ************************************************************************ @@ -420,7 +416,7 @@ class MyCustomGame(CustomGame): ''') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): continue v = w.variable.get() if w.widget in ('menu', 'preset'): @@ -435,7 +431,7 @@ class MyCustomGame(CustomGame): # escape v = v.replace('\\', '\\\\') v = v.replace("'", "\\'") - if isinstance(v, unicode): + if isinstance(v, six.text_type): v = v.encode('utf-8') if not v: v = 'Invalid Game Name' @@ -456,7 +452,7 @@ registerCustomGame(MyCustomGame) def reset_wizard(game): for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, six.string_types): continue if game is None: # set to default