From 9ec4dbd088268563659207184b317b8b3b9d34d2 Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Tue, 14 Feb 2023 19:55:23 +0100 Subject: [PATCH 1/3] Apply the following pylint messages: - use-list-literal - use-dict-literal - consider-using-in - consider-using-from-import --- .pylintrc | 8 ++++++++ dataobjs.py | 37 ++++++++++++++++++------------------- memos.py | 6 +++--- menus.py | 4 +--- parsetools.py | 2 +- pyinst.py | 12 ++++++------ toast.py | 4 ++-- user_profile.py | 2 +- 8 files changed, 40 insertions(+), 35 deletions(-) diff --git a/.pylintrc b/.pylintrc index 32810f6..315428d 100644 --- a/.pylintrc +++ b/.pylintrc @@ -160,6 +160,14 @@ enable=F, # Fatal wildcard-import, # Specific refactoring checks: use-implicit-booleaness-not-len, + useless-object-inheritance, + consider-using-from-import, + consider-using-in, + consider-using-join, + use-list-literal, + use-dict-literal, + useless-object-inheritance, + useless-return, # Specific basic checks: lost-exception, assert-on-tuple, diff --git a/dataobjs.py b/dataobjs.py index 372ddc4..f92349c 100644 --- a/dataobjs.py +++ b/dataobjs.py @@ -166,7 +166,7 @@ class pesterQuirks: # Exclude option is checked if checkstate == 2: # Check for substring that should be excluded. - excludes = list() + excludes = [] # Check for links, store in list. for match in re.finditer(_urlre, string): excludes.append(match) @@ -189,7 +189,7 @@ class pesterQuirks: if excludes[n].end() > excludes[n + 1].start(): excludes.pop(n) # Seperate parts to be quirked. - sendparts = list() + sendparts = [] # Add string until start of exclude at index 0. until = excludes[0].start() sendparts.append(string[:until]) @@ -203,10 +203,10 @@ class pesterQuirks: sendparts.append(string[after:]) # Quirk to-be-quirked parts. - recvparts = list() + recvparts = [] for part in sendparts: # No split, apply like normal. - if q.type == "regexp" or q.type == "random": + if q.type in ("regexp", "random"): recvparts.append( q.apply(part, first=(i == 0), last=lastStr) ) @@ -227,8 +227,8 @@ class pesterQuirks: string += recvparts[-1] else: # No split, apply like normal. - if q.type != "prefix" and q.type != "suffix": - if q.type == "regexp" or q.type == "random": + if q.type not in ("prefix", "suffix"): + if q.type in ("regexp", "random"): string = q.apply(string, first=(i == 0), last=lastStr) else: string = q.apply(string) @@ -238,8 +238,8 @@ class pesterQuirks: string = q.apply(string) else: # No split, apply like normal. - if q.type != "prefix" and q.type != "suffix": - if q.type == "regexp" or q.type == "random": + if q.type not in ("prefix", "suffix"): + if q.type in ("regexp", "random"): string = q.apply(string, first=(i == 0), last=lastStr) else: string = q.apply(string) @@ -396,22 +396,21 @@ class PesterProfile: ) def memoclosemsg(self, syscolor, initials, verb): - if type(initials) == type(list()): + if isinstance(initials, list): return "{} {}.".format( syscolor.name(), self.colorhtml(), ", ".join(initials), verb, ) - else: - return "{}{}{} {}.".format( - syscolor.name(), - self.colorhtml(), - initials.pcf, - self.initials(), - initials.number, - verb, - ) + return "{}{}{} {}.".format( + syscolor.name(), + self.colorhtml(), + initials.pcf, + self.initials(), + initials.number, + verb, + ) def memonetsplitmsg(self, syscolor, initials): if len(initials) <= 0: @@ -439,7 +438,7 @@ class PesterProfile: def memobanmsg(self, opchum, opgrammar, syscolor, initials, reason): opinit = opgrammar.pcf + opchum.initials() + opgrammar.number - if type(initials) == type(list()): + if isinstance(initials, list): if opchum.handle == reason: return ( "{} banned {} from responding to memo.".format( diff --git a/memos.py b/memos.py index 37744d2..8c942a5 100644 --- a/memos.py +++ b/memos.py @@ -107,7 +107,7 @@ class TimeGrammar: self.temporal = temporal self.pcf = pcf self.when = when - if number == "0" or number == 0: + if number in ("0", 0): self.number = "" else: self.number = str(number) @@ -164,7 +164,7 @@ class TimeTracker(list): except TypeError: # (temporal, pcf, when) = pcfGrammar(mysteryTime()) pcf = pcfGrammar(mysteryTime())[1] - if pcf == "C" or pcf == "?": + if pcf in ("C", "?"): return if timed in self.timerecord[pcf]: return @@ -176,7 +176,7 @@ class TimeTracker(list): pcf = pcfGrammar(timed - timedelta(0))[1] except TypeError: pcf = pcfGrammar(mysteryTime())[1] - if pcf == "C" or pcf == "?": + if pcf in ("C", "?"): return 0 if len(self.timerecord[pcf]) > 1: return self.timerecord[pcf].index(timed) + 1 diff --git a/menus.py b/menus.py index 61555fd..8468695 100644 --- a/menus.py +++ b/menus.py @@ -37,9 +37,7 @@ class PesterQuirkItem(QtWidgets.QTreeWidgetItem): """Sets the order of quirks if auto-sorted by Qt. Obsolete now.""" if self.quirk.type == "prefix": return True - elif ( - self.quirk.type == "replace" or self.quirk.type == "regexp" - ) and quirkitem.type == "suffix": + elif self.quirk.type in ("replace", "regexp") and quirkitem.type == "suffix": return True else: return False diff --git a/parsetools.py b/parsetools.py index 19fb1d3..954c866 100644 --- a/parsetools.py +++ b/parsetools.py @@ -13,7 +13,7 @@ except ImportError: import dataobjs # karxi: My own contribution to this - a proper lexer. -import pnc.lexercon as lexercon +from pnc import lexercon from generic import mysteryTime from quirks import ScriptQuirks from pyquirks import PythonQuirks diff --git a/pyinst.py b/pyinst.py index 9b994c7..eb47b2f 100644 --- a/pyinst.py +++ b/pyinst.py @@ -238,10 +238,10 @@ if (_ARGUMENTS.prompts is not False) and (_ARGUMENTS.prompts != "False"): "This is a script to make building with Pyinstaller a bit more conventient." ) - while (delete_builddist != "y") and (delete_builddist != "n"): + while delete_builddist not in ("y", "n"): delete_builddist = input("Delete build & dist folders? (Y/N): ").lower() - while (upx_enabled != "y") and (upx_enabled != "n"): + while upx_enabled not in ("y", "n"): upx_enabled = input("Enable UPX? (Y/N): ").lower() if upx_enabled == "y": print("If upx is on your path you don't need to include anything here.") @@ -257,14 +257,14 @@ if (_ARGUMENTS.prompts is not False) and (_ARGUMENTS.prompts != "False"): elif upx_enabled == "n": upx_dir = "" - while (windowed != "y") and (windowed != "n"): + while windowed not in ("y", "n"): windowed = input("Build with '--windowed'? (Y/N): ").lower() if sys.platform == "win32": print( "(https://pyinstaller.readthedocs.io/en/stable/usage.html?highlight=sdk#windows)" ) - while (package_universal_crt != "y") and (package_universal_crt != "n"): + while package_universal_crt not in ("y", "n"): package_universal_crt = input( "Try to include universal CRT? (Y/N): " ).lower() @@ -303,8 +303,8 @@ if (_ARGUMENTS.prompts is not False) and (_ARGUMENTS.prompts != "False"): ) print("crt_path = " + crt_path) - if (sys.platform == "win32") or (sys.platform == "linux"): - while (onefile != "y") and (onefile != "n"): + if sys.platform in ("win32", "linux"): + while onefile not in ("y", "n"): onefile = input("Build with '--onefile'? (Y/N): ").lower() except KeyboardInterrupt: diff --git a/toast.py b/toast.py index 8c32aa9..04e914c 100644 --- a/toast.py +++ b/toast.py @@ -93,7 +93,7 @@ class ToastMachine: def show(self): if self.machine.on: # Use libnotify's queue if using libnotify - if self.machine.type == "libnotify" or self.machine.type == "twmn": + if self.machine.type in ("libnotify", "twmn"): self.realShow() elif self.machine.toasts: self.machine.toasts.append(self) @@ -116,7 +116,7 @@ class ToastMachine: extras["parent"] = self.machine.parent if "time" in args: extras["time"] = self.time - if k == "libnotify" or k == "twmn": + if k in ("libnotify", "twmn"): t = v(self.title, self.msg, self.icon, **extras) else: t = v(self.machine, self.title, self.msg, self.icon, **extras) diff --git a/user_profile.py b/user_profile.py index 83e9448..d50077d 100644 --- a/user_profile.py +++ b/user_profile.py @@ -849,7 +849,7 @@ class PesterProfileDB(dict): u = [] for handle, c in chumdict.items(): - options = dict() + options = {} if "group" in c: options["group"] = c["group"] if "notes" in c: From 370685f6b346ffa15903405ea29903727224978a Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Wed, 15 Feb 2023 16:29:20 +0100 Subject: [PATCH 2/3] Remove AttrDict and enable pylint typecheck message category. The AttrDict class had Python 2 leftovers which the linter flagged and isn't really necessary anyway, plus it wasn't licensed under the GPL. --- .pylintrc | 3 +- convo.py | 23 ++++--- pesterchum.py | 79 ++++++++++++------------ pnc/dep/attrdict.py | 146 -------------------------------------------- pnc/unicolor.py | 6 +- 5 files changed, 52 insertions(+), 205 deletions(-) delete mode 100644 pnc/dep/attrdict.py diff --git a/.pylintrc b/.pylintrc index 315428d..e336a72 100644 --- a/.pylintrc +++ b/.pylintrc @@ -26,7 +26,7 @@ extension-pkg-allow-list= # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. (This is an alternative name to extension-pkg-allow-list # for backward compatibility.) -extension-pkg-whitelist= +extension-pkg-whitelist=seccomp # Return non-zero exit code if any of these messages/categories are detected, # even if score is above --fail-under value. Syntax same as enable. Messages @@ -156,6 +156,7 @@ enable=F, # Fatal spelling, string, nonascii-checker, + typecheck, # Specific import checks: wildcard-import, # Specific refactoring checks: diff --git a/convo.py b/convo.py index 50e9ac7..8dabefb 100644 --- a/convo.py +++ b/convo.py @@ -14,7 +14,6 @@ except ImportError: from dataobjs import PesterHistory from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, smiledict import parsetools -from pnc.dep.attrdict import AttrDict PchumLog = logging.getLogger("pchumLogger") @@ -33,33 +32,33 @@ class PesterTabWindow(QtWidgets.QFrame): self.tabs.tabCloseRequested[int].connect(self.tabClose) self.tabs.tabMoved[int, int].connect(self.tabMoved) - self.shortcuts = AttrDict() - self.shortcuts.tabNext = QShortcut( + self.shortcuts = {} + self.shortcuts["tabNext"] = QShortcut( QtGui.QKeySequence("Ctrl+j"), self, context=QtCore.Qt.ShortcutContext.WidgetWithChildrenShortcut, ) - self.shortcuts.tabLast = QShortcut( + self.shortcuts["tabLast"] = QShortcut( QtGui.QKeySequence("Ctrl+k"), self, context=QtCore.Qt.ShortcutContext.WidgetWithChildrenShortcut, ) # Note that we use reversed keys here. - self.shortcuts.tabUp = QShortcut( + self.shortcuts["tabUp"] = QShortcut( QtGui.QKeySequence("Ctrl+PgDown"), self, context=QtCore.Qt.ShortcutContext.WidgetWithChildrenShortcut, ) - self.shortcuts.tabDn = QShortcut( + self.shortcuts["tabDn"] = QShortcut( QtGui.QKeySequence("Ctrl+PgUp"), self, context=QtCore.Qt.ShortcutContext.WidgetWithChildrenShortcut, ) - self.shortcuts.tabNext.activated.connect(self.nudgeTabNext) - self.shortcuts.tabUp.activated.connect(self.nudgeTabNext) - self.shortcuts.tabLast.activated.connect(self.nudgeTabLast) - self.shortcuts.tabDn.activated.connect(self.nudgeTabLast) + self.shortcuts["tabNext"].activated.connect(self.nudgeTabNext) + self.shortcuts["tabUp"].activated.connect(self.nudgeTabNext) + self.shortcuts["tabLast"].activated.connect(self.nudgeTabLast) + self.shortcuts["tabDn"].activated.connect(self.nudgeTabLast) self.initTheme(self.mainwindow.theme) self.layout = QtWidgets.QVBoxLayout() @@ -544,7 +543,7 @@ class PesterText(QtWidgets.QTextEdit): window.chatlog.log(parent.chum.handle, lexmsg) else: if ( - (window.idler.auto or window.idler.manual) + (window.idler["auto"] or window.idler["manual"]) and parent.chumopen and not parent.isBot(chum.handle) ): @@ -675,7 +674,7 @@ class PesterInput(QtWidgets.QLineEdit): self.setText(prev) elif event.key() in [QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown]: self.parent().textArea.keyPressEvent(event) - self.parent().mainwindow.idler.time = 0 + self.parent().mainwindow.idler["time"] = 0 super().keyPressEvent(event) diff --git a/pesterchum.py b/pesterchum.py index 8740729..73543c6 100755 --- a/pesterchum.py +++ b/pesterchum.py @@ -23,7 +23,6 @@ if ostools.isLinux(): import libseccomp # import console -from pnc.dep.attrdict import AttrDict from user_profile import ( userConfig, userProfile, @@ -162,8 +161,8 @@ BOTNAMES.extend(SERVICES) # Save the main app. From here, we should be able to get everything else in # order, for console use. _CONSOLE = False -_CONSOLE_ENV = AttrDict() -_CONSOLE_ENV.PAPP = None +_CONSOLE_ENV = {} +_CONSOLE_ENV["PAPP"] = None # Python 3 QString = str # Command line arguments @@ -1313,7 +1312,7 @@ class PesterWindow(MovingWindow): ), ) # For debugging - _CONSOLE_ENV.PAPP = self + _CONSOLE_ENV["PAPP"] = self # TODO: karxi: SO! At the end of this function it seems like that # object is just made into None or.../something/. Somehow, it just # DIES, and I haven't the slightest idea why. I've tried multiple ways @@ -1332,7 +1331,7 @@ class PesterWindow(MovingWindow): self.memos = CaseInsensitiveDict() self.tabconvo = None self.tabmemo = None - self.shortcuts = AttrDict() + self.shortcuts = {} self.setAutoFillBackground(False) self.setObjectName("main") @@ -1637,26 +1636,24 @@ class PesterWindow(MovingWindow): self.waitingMessages = waitingMessageHolder(self) - self.idler = AttrDict( - dict( - # autoidle - auto=False, - # setidle - manual=False, - # idlethreshold - threshold=60 * self.config.idleTime(), - # idleaction - action=self.idleaction, - # idletimer - timer=QtCore.QTimer(self), - # idleposition - pos=QtGui.QCursor.pos(), - # idletime - time=0, - ) - ) - self.idler.timer.timeout.connect(self.checkIdle) - self.idler.timer.start(1000) + self.idler = { + # autoidle + "auto": False, + # setidle + "manual": False, + # idlethreshold + "threshold": 60 * self.config.idleTime(), + # idleaction + "action": self.idleaction, + # idletimer + "timer": QtCore.QTimer(self), + # idleposition + "pos": QtGui.QCursor.pos(), + # idletime + "time": 0, + } + self.idler["timer"].timeout.connect(self.checkIdle) + self.idler["timer"].start(1000) if not self.config.defaultprofile(): self.changeProfile() @@ -2912,49 +2909,49 @@ class PesterWindow(MovingWindow): def toggleIdle(self, idle): if idle: # We checked the box to go idle. - self.idler.manual = True + self.idler["manual"] = True self.setAway.emit(True) self.randhandler.setIdle(True) self._sendIdleMsgs() else: - self.idler.manual = False + self.idler["manual"] = False self.setAway.emit(False) self.randhandler.setIdle(False) - self.idler.time = 0 + self.idler["time"] = 0 # karxi: TODO: Need to consider sticking an idle-setter here. @QtCore.pyqtSlot() def checkIdle(self): newpos = QtGui.QCursor.pos() - oldpos = self.idler.pos + oldpos = self.idler["pos"] # Save the new position. - self.idler.pos = newpos + self.idler["pos"] = newpos - if self.idler.manual: + if self.idler["manual"]: # We're already idle, because the user said to be. - self.idler.time = 0 + self.idler["time"] = 0 return - elif self.idler.auto: - self.idler.time = 0 + elif self.idler["auto"]: + self.idler["time"] = 0 if newpos != oldpos: # Cursor moved; unset idle. - self.idler.auto = False + self.idler["auto"] = False self.setAway.emit(False) self.randhandler.setIdle(False) return if newpos != oldpos: # Our cursor has moved, which means we can't be idle. - self.idler.time = 0 + self.idler["time"] = 0 return # If we got here, WE ARE NOT IDLE, but may become so - self.idler.time += 1 - if self.idler.time >= self.idler.threshold: + self.idler["time"] += 1 + if self.idler["time"] >= self.idler["threshold"]: # We've been idle for long enough to fall automatically idle. - self.idler.auto = True + self.idler["auto"] = True # We don't need this anymore. - self.idler.time = 0 + self.idler["time"] = 0 # Make it clear that we're idle. self.setAway.emit(True) self.randhandler.setIdle(True) @@ -3369,7 +3366,7 @@ class PesterWindow(MovingWindow): curidle = self.config.idleTime() if idlesetting != curidle: self.config.set("idleTime", idlesetting) - self.idler.threshold = 60 * idlesetting + self.idler["threshold"] = 60 * idlesetting # theme ghostchumsetting = self.optionmenu.ghostchum.isChecked() curghostchum = self.config.ghostchum() diff --git a/pnc/dep/attrdict.py b/pnc/dep/attrdict.py deleted file mode 100644 index dea6063..0000000 --- a/pnc/dep/attrdict.py +++ /dev/null @@ -1,146 +0,0 @@ -# Heavily modified version of the code featured at the given link -## {{{ http://code.activestate.com/recipes/473786/ (r1) -class AttrDict(dict): - """A dictionary with attribute-style access. It maps attribute access to - the real dictionary. - - Note that accesses to preexisting (e.g. class inherited) or reserved - attributes are handled as they would be normally, and will not be - overwritten. - Overload _is_reserved if you want to change this.""" - - def __init__(self, init={}): - super().__init__(init) - - def __getstate__(self): - return list(self.__dict__.items()) - - def __setstate__(self, items): - for key, val in items: - self.__dict__[key] = val - - def __repr__(self): - return f"{type(self).__name__}({super().__repr__()})" - - def __setitem__(self, name, value): - return super().__setitem__(name, value) - - def __getitem__(self, name): - return super().__getitem__(name) - - def __delitem__(self, name): - return super().__delitem__(name) - - def __getattr__(self, name): - # NOTE: __getattr__ is called if the code has already failed to access - # an attribute on this object. The rest of this code reflects this. - # We could override __getattribute__ to bypass this, but that's not - # worthwhile. - - # We don't do any special handling for reserved names. - if self._is_reserved(name): - # Fall back to normal handling, by force. - return object.__getattribute__(self, name) - - try: - # Try to __getitem__. - result = self[name] - except (KeyError, AttributeError): - # Raising KeyError here will confuse __deepcopy__, so don't do - # that. - # Throw a custom error. - raise AttributeError(f"No key/attr {name!r}") - return result - - def __setattr__(self, name, value): - # Set to the attribute first if it's defined. - # (NOTE: This isn't subject to the same checking as __getattr__.) - # Using dir() also checks non-instance definitions, so things defined - # on a class can be easily set on an instance this way. - - # Detect special/reserved names. - if name in dir(self) or self._is_reserved(name): - # Set it if it's 'special' because we aren't supposed to touch any - # of that - too many potential implementation issues. - # - # Apparently we're also not supposed to set our own dict directly - # in this particular function?... - return object.__setattr__(self, name, value) - else: - return super().__setitem__(name, value) - - def __delattr__(self, name): - # We very *specifically* use self.__dict__ here, because we couldn't - # possibly delete a value that doesn't yet *exist* in our instance's - # namespace yet! - # This shouldn't be a problem, since this type should never have - # __slots__. - if name in self.__dict__: - # See __setattr__. - return object.__delattr__(self, name) - else: - try: - del self[name] - except KeyError as err: - raise AttributeError(str(err)) - - @staticmethod - def _is_reserved(name): - """Check if an attribute name is reserved for system use.""" - # A very simple method. - result = name[:2] == name[-2:] == "__" - return result - - def copy(self): - return type(self)(self) - - __copy__ = copy - - -## end of http://code.activestate.com/recipes/473786/ }}} - - -class DefAttrDict(AttrDict): - default_factory = None - - def __init__(self, default_factory=None, *args, **kwargs): - self.default_factory = default_factory - super().__init__(*args, **kwargs) - - def __repr__(self): - return "{}({!r}, {})".format( - type(self).__name__, - self.default_factory, - # We skip normal processing here, since AttrDict provides basic - # repr for classes in general, which we don't want. - dict.__repr__(self), - ) - - def __getitem__(self, name): - try: - result = super().__getitem__(name) - except KeyError: - result = None - if self.default_factory is not None: - result = self.default_factory() - self[name] = result - return result - - def __getattr__(self, name): - try: - result = super().__getattr__(name) - except AttributeError: - # Detect special/reserved names. - if self._is_reserved(name): - # We shouldn't automatically fill these in. - # Pass this along. - raise - return result - - def copy(self): - return type(self)(self.default_factory, self) - - __copy__ = copy - - -# vim: set autoindent ts=4 sts=4 sw=4 textwidth=79 expandtab: diff --git a/pnc/unicolor.py b/pnc/unicolor.py index e2e9f9e..8334a2f 100644 --- a/pnc/unicolor.py +++ b/pnc/unicolor.py @@ -2,10 +2,6 @@ __all__ = ["Color"] # karxi: Copied from my old Textsub script. Please forgive the mess, and keep # in mind that this may be phased out in the future. - - -from pnc.dep.attrdict import AttrDict - import collections import functools import sys @@ -410,7 +406,7 @@ class Color: # All of these are effectively equivalent to the Qt-provided colors, so they # could be phased out - but there's no need to, yet. -_svg_colors = AttrDict() +_svg_colors = {} _irc_colors = {} _svg_colors.update( { From 64538b2644df08ee2905d2def4621de7a4c93180 Mon Sep 17 00:00:00 2001 From: Dpeta <69427753+Dpeta@users.noreply.github.com> Date: Wed, 15 Feb 2023 17:01:27 +0100 Subject: [PATCH 3/3] Use isinstance() for typechecks. --- .pylintrc | 3 +++ convo.py | 4 ++-- dataobjs.py | 6 +++--- generic.py | 4 ++-- memos.py | 16 ++++++++-------- menus.py | 2 +- parsetools.py | 8 ++++---- pytwmn.py | 2 +- user_profile.py | 4 ++-- 9 files changed, 26 insertions(+), 23 deletions(-) diff --git a/.pylintrc b/.pylintrc index e336a72..f3124d3 100644 --- a/.pylintrc +++ b/.pylintrc @@ -165,6 +165,9 @@ enable=F, # Fatal consider-using-from-import, consider-using-in, consider-using-join, + consider-merging-isinstance, + isinstance-second-argument-not-valid-type, + unidiomatic-typecheck, use-list-literal, use-dict-literal, useless-object-inheritance, diff --git a/convo.py b/convo.py index 8dabefb..23e7ca1 100644 --- a/convo.py +++ b/convo.py @@ -377,7 +377,7 @@ class PesterText(QtWidgets.QTextEdit): self.mainwindow = self.parent().mainwindow else: self.mainwindow = self.parent() - if type(parent.parent) is PesterTabWindow: + if isinstance(parent.parent, PesterTabWindow): self.tabobject = parent.parent() self.hasTabs = True else: @@ -514,7 +514,7 @@ class PesterText(QtWidgets.QTextEdit): imsg = chum.idlemsg(systemColor, window.theme["convo/text/idle"]) window.chatlog.log(chum.handle, imsg) self.append(convertTags(imsg)) - elif type(lexmsg[0]) is mecmd: + elif isinstance(lexmsg[0], mecmd): memsg = chum.memsg(systemColor, lexmsg) if chum is me: window.chatlog.log(parent.chum.handle, memsg) diff --git a/dataobjs.py b/dataobjs.py index f92349c..cfc0c77 100644 --- a/dataobjs.py +++ b/dataobjs.py @@ -35,7 +35,7 @@ _handlere = re.compile(r"(\s|^)(@[A-Za-z0-9_]+)") class pesterQuirk: def __init__(self, quirk): - if type(quirk) != dict: + if not isinstance(quirk, dict): raise ValueError("Quirks must be given a dictionary") self.quirk = quirk self.type = self.quirk["type"] @@ -136,9 +136,9 @@ class pesterQuirks: return [q.quirk for q in self.quirklist] def addQuirk(self, q): - if type(q) == dict: + if isinstance(q, dict): self.quirklist.append(pesterQuirk(q)) - elif type(q) == pesterQuirk: + elif isinstance(q, pesterQuirk): self.quirklist.append(q) def apply(self, lexed, first=False, last=False): diff --git a/generic.py b/generic.py index 020aeeb..a013854 100644 --- a/generic.py +++ b/generic.py @@ -11,10 +11,10 @@ class mysteryTime(timedelta): return self def __eq__(self, other): - return type(other) is mysteryTime + return isinstance(other, mysteryTime) def __neq__(self, other): - return type(other) is not mysteryTime + return not isinstance(other, mysteryTime) class CaseInsensitiveDict(dict): diff --git a/memos.py b/memos.py index 8c942a5..4875645 100644 --- a/memos.py +++ b/memos.py @@ -32,7 +32,7 @@ QString = str def delta2txt(d, format="pc"): - if type(d) is mysteryTime: + if isinstance(d, mysteryTime): return "?" if format == "pc": sign = "+" if d >= timedelta(0) else "-" @@ -117,7 +117,7 @@ class TimeTracker(list): def __init__(self, time=None): # mysteryTime breaks stuff now, so, uh # I'm replacing it with 1 day... - if type(time) == mysteryTime: + if isinstance(time, mysteryTime): time = timedelta(microseconds=1) self.timerecord = {"P": [], "F": []} self.open = {} @@ -131,7 +131,7 @@ class TimeTracker(list): def addTime(self, timed): # mysteryTime :] - if type(lexmsg[0]) is colorBegin: # get color tag + if isinstance(lexmsg[0], colorBegin): # get color tag colortag = lexmsg[0] try: color = QtGui.QColor(*[int(c) for c in colortag.color.split(",")]) @@ -419,7 +419,7 @@ class MemoText(PesterText): msg = msg + "" return '' + msg + "" - if type(lexmsg[0]) is mecmd: + if isinstance(lexmsg[0], mecmd): memsg = chum.memsg(systemColor, lexmsg, time=time.getGrammar()) window.chatlog.log(parent.channel, memsg) self.append(convertTags(memsg)) @@ -721,7 +721,7 @@ class PesterMemo(PesterConvo): c.setForeground(QtGui.QBrush(color)) def addMessage(self, text, handle): - if type(handle) is bool: + if isinstance(handle, bool): chum = self.mainwindow.profile() else: chum = PesterProfile(handle) diff --git a/menus.py b/menus.py index 8468695..491aca8 100644 --- a/menus.py +++ b/menus.py @@ -101,7 +101,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget): self.changeCheckState() def currentQuirk(self): - if type(self.currentItem()) is PesterQuirkItem: + if isinstance(self.currentItem(), PesterQuirkItem): return self.currentItem() else: return None diff --git a/parsetools.py b/parsetools.py index 954c866..1c2c55c 100644 --- a/parsetools.py +++ b/parsetools.py @@ -310,10 +310,10 @@ def lexMessage(string): beginc = 0 endc = 0 for o in lexed: - if type(o) is colorBegin: + if isinstance(o, colorBegin): beginc += 1 balanced.append(o) - elif type(o) is colorEnd: + elif isinstance(o, colorEnd): if beginc >= endc: endc += 1 balanced.append(o) @@ -942,9 +942,9 @@ class parseLeaf: def expand(self, mo): out = "" for n in self.nodes: - if type(n) == parseLeaf: + if isinstance(n, parseLeaf): out += n.expand(mo) - elif type(n) == backreference: + elif isinstance(n, backreference): out += mo.group(int(n.number)) else: out += n diff --git a/pytwmn.py b/pytwmn.py index 641af53..b88023c 100755 --- a/pytwmn.py +++ b/pytwmn.py @@ -45,7 +45,7 @@ def init(host="127.0.0.1", port=None): break except OSError: raise TwmnError(TwmnError.NO_CONF) - if type(port) == type(""): + if isinstance(port, str): port = int(port) global s s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) diff --git a/user_profile.py b/user_profile.py index d50077d..8cc4731 100644 --- a/user_profile.py +++ b/user_profile.py @@ -373,7 +373,7 @@ with a backup from: %s" self.set("chums", newchums) def removeChum(self, chum): - if type(chum) is PesterProfile: + if isinstance(chum, PesterProfile): handle = chum.handle else: handle = chum @@ -605,7 +605,7 @@ class userProfile: def __init__(self, user): self.profiledir = _datadir + "profiles" - if type(user) is PesterProfile: + if isinstance(user, PesterProfile): self.chat = user self.userprofile = { "handle": user.handle,