From 5b6d5d153f91039b7cc36677abdaeda4fae21f7c Mon Sep 17 00:00:00 2001
From: Dpeta <69427753+Dpeta@users.noreply.github.com>
Date: Sat, 14 Jan 2023 22:59:59 +0100
Subject: [PATCH] Run all scripts through "pyupgrade --py38-plus"
---
convo.py | 22 +++++++-------
dataobjs.py | 61 +++++++++++++++++++-------------------
generic.py | 20 ++++++-------
irc.py | 40 +++++++++++++------------
logviewer.py | 14 ++++-----
memos.py | 16 +++++-----
menus.py | 6 ++--
mood.py | 2 +-
oyoyo/client.py | 10 +++----
oyoyo/cmdhandler.py | 12 ++++----
oyoyo/helpers.py | 16 ++++++----
oyoyo/services.py | 4 +--
parsetools.py | 42 +++++++++++++-------------
pesterchum.py | 72 +++++++++++++++++++++------------------------
pnc/dep/attrdict.py | 23 +++++++--------
pnc/lexercon.py | 9 ++----
pnc/unicolor.py | 10 ++-----
profile.py | 56 ++++++++++++++++++-----------------
pytwmn.py | 6 ++--
quirks.py | 6 ++--
toast.py | 6 ++--
21 files changed, 228 insertions(+), 225 deletions(-)
diff --git a/convo.py b/convo.py
index 7de6644..5e240d7 100644
--- a/convo.py
+++ b/convo.py
@@ -23,7 +23,7 @@ PchumLog = logging.getLogger("pchumLogger")
class PesterTabWindow(QtWidgets.QFrame):
def __init__(self, mainwindow, parent=None, convo="convo"):
- super(PesterTabWindow, self).__init__(parent)
+ super().__init__(parent)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
self.mainwindow = mainwindow
@@ -337,7 +337,7 @@ class PesterTabWindow(QtWidgets.QFrame):
class PesterMovie(QtGui.QMovie):
def __init__(self, parent):
- super(PesterMovie, self).__init__(parent)
+ super().__init__(parent)
self.textwindow = parent
@QtCore.pyqtSlot(int)
@@ -374,7 +374,7 @@ class PesterMovie(QtGui.QMovie):
class PesterText(QtWidgets.QTextEdit):
def __init__(self, theme, parent=None):
- super(PesterText, self).__init__(parent)
+ super().__init__(parent)
if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow
else:
@@ -594,7 +594,7 @@ class PesterText(QtWidgets.QTextEdit):
parent.textInput.keyPressEvent(event)
# Pass to the normal handler.
- super(PesterText, self).keyPressEvent(event)
+ super().keyPressEvent(event)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.MouseButton.LeftButton:
@@ -647,7 +647,7 @@ class PesterInput(QtWidgets.QLineEdit):
stylesheet_path = "convo/input/style"
def __init__(self, theme, parent=None):
- super(PesterInput, self).__init__(parent)
+ super().__init__(parent)
self.changeTheme(theme)
def changeTheme(self, theme):
@@ -662,7 +662,7 @@ class PesterInput(QtWidgets.QLineEdit):
def focusInEvent(self, event):
self.parent().clearNewMessage()
self.parent().textArea.textCursor().clearSelection()
- super(PesterInput, self).focusInEvent(event)
+ super().focusInEvent(event)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key.Key_Up:
@@ -677,12 +677,12 @@ class PesterInput(QtWidgets.QLineEdit):
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
- super(PesterInput, self).keyPressEvent(event)
+ super().keyPressEvent(event)
class PesterConvo(QtWidgets.QFrame):
def __init__(self, chum, initiated, mainwindow, parent=None):
- super(PesterConvo, self).__init__(parent)
+ super().__init__(parent)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setObjectName(chum.handle)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
@@ -691,7 +691,7 @@ class PesterConvo(QtWidgets.QFrame):
theme = self.mainwindow.theme
self.resize(*theme["convo/size"])
self.setStyleSheet(
- "QtWidgets.QFrame#%s { %s }" % (chum.handle, theme["convo/style"])
+ "QtWidgets.QFrame#{} {{ {} }}".format(chum.handle, theme["convo/style"])
)
self.setWindowIcon(self.icon())
self.setWindowTitle(self.title())
@@ -1012,7 +1012,9 @@ class PesterConvo(QtWidgets.QFrame):
def changeTheme(self, theme):
self.resize(*theme["convo/size"])
self.setStyleSheet(
- "QtWidgets.QFrame#%s { %s }" % (self.chum.handle, theme["convo/style"])
+ "QtWidgets.QFrame#{} {{ {} }}".format(
+ self.chum.handle, theme["convo/style"]
+ )
)
margins = theme["convo/margins"]
diff --git a/dataobjs.py b/dataobjs.py
index 1d63f4b..11eba6c 100644
--- a/dataobjs.py
+++ b/dataobjs.py
@@ -34,7 +34,7 @@ _memore = re.compile(r"(\s|^)(#[A-Za-z0-9_]+)")
_handlere = re.compile(r"(\s|^)(@[A-Za-z0-9_]+)")
-class pesterQuirk(object):
+class pesterQuirk:
def __init__(self, quirk):
if type(quirk) != dict:
raise ValueError("Quirks must be given a dictionary")
@@ -112,14 +112,14 @@ class pesterQuirk(object):
elif self.type == "suffix":
return "END WITH: %s" % (self.quirk["value"])
elif self.type == "replace":
- return "REPLACE %s WITH %s" % (self.quirk["from"], self.quirk["to"])
+ return "REPLACE {} WITH {}".format(self.quirk["from"], self.quirk["to"])
elif self.type == "regexp":
- return "REGEXP: %s REPLACED WITH %s" % (
+ return "REGEXP: {} REPLACED WITH {}".format(
self.quirk["from"],
self.quirk["to"],
)
elif self.type == "random":
- return "REGEXP: %s RANDOMLY REPLACED WITH %s" % (
+ return "REGEXP: {} RANDOMLY REPLACED WITH {}".format(
self.quirk["from"],
[r for r in self.quirk["randomlist"]],
)
@@ -127,7 +127,7 @@ class pesterQuirk(object):
return "MISPELLER: %d%%" % (self.quirk["percentage"])
-class pesterQuirks(object):
+class pesterQuirks:
def __init__(self, quirklist):
self.quirklist = []
for q in quirklist:
@@ -258,11 +258,10 @@ class pesterQuirks(object):
return final
def __iter__(self):
- for q in self.quirklist:
- yield q
+ yield from self.quirklist
-class PesterProfile(object):
+class PesterProfile:
def __init__(
self,
handle,
@@ -345,12 +344,12 @@ class PesterProfile(object):
msg = convertTags(lexmsg[1:], "text")
uppersuffix = suffix.upper()
if time is not None:
- handle = "%s %s" % (time.temporal, self.handle)
+ handle = f"{time.temporal} {self.handle}"
initials = time.pcf + self.initials() + time.number + uppersuffix
else:
handle = self.handle
initials = self.initials() + uppersuffix
- return "-- %s%s [%s] %s --" % (
+ return "-- {}{} [{}] {} --".format(
syscolor.name(),
handle,
suffix,
@@ -360,7 +359,7 @@ class PesterProfile(object):
)
def pestermsg(self, otherchum, syscolor, verb):
- return "-- %s [%s] %s %s [%s] at %s --" % (
+ return "-- {} [{}] {} {} [{}] at {} --".format(
syscolor.name(),
self.handle,
self.colorhtml(),
@@ -386,7 +385,7 @@ class PesterProfile(object):
)
def idlemsg(self, syscolor, verb):
- return "-- %s [%s] %s --" % (
+ return "-- {} [{}] {} --".format(
syscolor.name(),
self.handle,
self.colorhtml(),
@@ -396,14 +395,14 @@ class PesterProfile(object):
def memoclosemsg(self, syscolor, initials, verb):
if type(initials) == type(list()):
- return "%s %s." % (
+ return "{} {}.".format(
syscolor.name(),
self.colorhtml(),
", ".join(initials),
verb,
)
else:
- return "%s%s%s %s." % (
+ return "{}{}{} {}.".format(
syscolor.name(),
self.colorhtml(),
initials.pcf,
@@ -416,7 +415,7 @@ class PesterProfile(object):
if len(initials) <= 0:
return "Netsplit quits: None" % (syscolor.name())
else:
- return "Netsplit quits: %s" % (
+ return "Netsplit quits: {}".format(
syscolor.name(),
", ".join(initials),
)
@@ -427,7 +426,7 @@ class PesterProfile(object):
PchumLog.debug("pre pcf+self.initials()")
initials = timeGrammar.pcf + self.initials()
PchumLog.debug("post pcf+self.initials()")
- return "%s %s %s %s." % (
+ return "{} {} {} {}.".format(
syscolor.name(),
self.colorhtml(),
initials,
@@ -440,11 +439,13 @@ class PesterProfile(object):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
if type(initials) == type(list()):
if opchum.handle == reason:
- return "%s banned %s from responding to memo." % (
- opchum.colorhtml(),
- opinit,
- self.colorhtml(),
- ", ".join(initials),
+ return (
+ "{} banned {} from responding to memo.".format(
+ opchum.colorhtml(),
+ opinit,
+ self.colorhtml(),
+ ", ".join(initials),
+ )
)
else:
return (
@@ -501,7 +502,7 @@ class PesterProfile(object):
def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s permabanned %s from the memo." % (
+ return "{} permabanned {} from the memo.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@@ -512,7 +513,7 @@ class PesterProfile(object):
# (temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when)
timetext = timeDifference(td)
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
- return "%s %s [%s] %s %s." % (
+ return "{} {} [{}] {} {}.".format(
syscolor.name(),
self.colorhtml(),
timeGrammar.temporal,
@@ -524,7 +525,7 @@ class PesterProfile(object):
def memoopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s made %s an OP." % (
+ return "{} made {} an OP.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@@ -533,7 +534,7 @@ class PesterProfile(object):
def memodeopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s took away %s's OP powers." % (
+ return "{} took away {}'s OP powers.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@@ -542,7 +543,7 @@ class PesterProfile(object):
def memovoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s gave %s voice." % (
+ return "{} gave {} voice.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@@ -551,7 +552,7 @@ class PesterProfile(object):
def memodevoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s took away %s's voice." % (
+ return "{} took away {}'s voice.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@@ -564,7 +565,7 @@ class PesterProfile(object):
modeon = "now"
else:
modeon = "no longer"
- return "Memo is %s %s by %s" % (
+ return "Memo is {} {} by {}".format(
syscolor.name(),
modeon,
modeverb,
@@ -574,7 +575,7 @@ class PesterProfile(object):
def memoquirkkillmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
- return "%s turned off your quirk." % (
+ return "{} turned off your quirk.".format(
syscolor.name(),
opchum.colorhtml(),
opinit,
@@ -598,7 +599,7 @@ class PesterProfile(object):
return (True,)
-class PesterHistory(object):
+class PesterHistory:
def __init__(self):
self.history = []
self.current = 0
diff --git a/generic.py b/generic.py
index 0f06980..3bf9297 100644
--- a/generic.py
+++ b/generic.py
@@ -19,19 +19,19 @@ class mysteryTime(timedelta):
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
- super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)
+ super().__setitem__(key.lower(), value)
def __getitem__(self, key):
- return super(CaseInsensitiveDict, self).__getitem__(key.lower())
+ return super().__getitem__(key.lower())
def __contains__(self, key):
- return super(CaseInsensitiveDict, self).__contains__(key.lower())
+ return super().__contains__(key.lower())
def has_key(self, key):
- return key.lower() in super(CaseInsensitiveDict, self)
+ return key.lower() in super()
def __delitem__(self, key):
- super(CaseInsensitiveDict, self).__delitem__(key.lower())
+ super().__delitem__(key.lower())
class PesterList(list):
@@ -41,7 +41,7 @@ class PesterList(list):
class PesterIcon(QtGui.QIcon):
def __init__(self, *x):
- super(PesterIcon, self).__init__(x[0])
+ super().__init__(x[0])
if type(x[0]) in [str, str]:
self.icon_pixmap = QtGui.QPixmap(x[0])
else:
@@ -86,7 +86,7 @@ class RightClickTree(QtWidgets.QTreeWidget):
class MultiTextDialog(QtWidgets.QDialog):
def __init__(self, title, parent, *queries):
- super(MultiTextDialog, self).__init__(parent)
+ super().__init__(parent)
self.setWindowTitle(title)
if len(queries) == 0:
return
@@ -131,7 +131,7 @@ class MovingWindow(QtWidgets.QFrame):
# https://doc.qt.io/qt-5/qwindow.html#startSystemMove
# This is also the only method that works on Wayland, which doesn't support setting position.
def __init__(self, *x, **y):
- super(MovingWindow, self).__init__(*x, **y)
+ super().__init__(*x, **y)
self.moving = None
self.moveupdate = 0
@@ -163,7 +163,7 @@ class MovingWindow(QtWidgets.QFrame):
self.moving = None
-class NoneSound(object):
+class NoneSound:
def __init__(self, *args, **kwargs):
pass
@@ -179,7 +179,7 @@ class NoneSound(object):
class WMButton(QtWidgets.QPushButton):
def __init__(self, icon, parent=None):
- super(WMButton, self).__init__(icon, "", parent)
+ super().__init__(icon, "", parent)
self.setIconSize(icon.realsize())
self.resize(icon.realsize())
self.setFlat(True)
diff --git a/irc.py b/irc.py
index dba6d0c..333fc40 100644
--- a/irc.py
+++ b/irc.py
@@ -96,10 +96,10 @@ class PesterIRC(QtCore.QThread):
except socket.timeout as se:
PchumLog.debug("timeout in thread %s" % (self))
self.cli.close()
- self.stopIRC = "%s, %s" % (type(se), se)
+ self.stopIRC = "{}, {}".format(type(se), se)
return
except (OSError, IndexError, ValueError) as se:
- self.stopIRC = "%s, %s" % (type(se), se)
+ self.stopIRC = "{}, {}".format(type(se), se)
PchumLog.debug("socket error, exiting thread")
return
else:
@@ -372,7 +372,7 @@ class PesterIRC(QtCore.QThread):
reason = str(l[1])
if len(l) > 2:
for x in l[2:]:
- reason += str(":") + str(x)
+ reason += ":" + str(x)
else:
reason = ""
try:
@@ -387,7 +387,7 @@ class PesterIRC(QtCore.QThread):
c = str(channel)
m = str(mode)
cmd = str(command)
- PchumLog.debug("c=%s\nm=%s\ncmd=%s" % (c, m, cmd))
+ PchumLog.debug("c={}\nm={}\ncmd={}".format(c, m, cmd))
if cmd == "":
cmd = None
try:
@@ -483,7 +483,7 @@ class PesterIRC(QtCore.QThread):
class PesterHandler(DefaultCommandHandler):
def notice(self, nick, chan, msg):
handle = nick[0 : nick.find("!")]
- PchumLog.info('---> recv "NOTICE %s :%s"' % (handle, msg))
+ PchumLog.info('---> recv "NOTICE {} :{}"'.format(handle, msg))
if (
handle == "ChanServ"
and chan == self.parent.mainwindow.profile().handle
@@ -501,13 +501,13 @@ class PesterHandler(DefaultCommandHandler):
mood = Mood(int(value))
self.parent.moodUpdated.emit(nick, mood)
except ValueError:
- PchumLog.warning("Invalid mood value, %s, %s" % (nick, mood))
+ PchumLog.warning("Invalid mood value, {}, {}".format(nick, mood))
elif key.lower() == "color":
color = QtGui.QColor(value) # Invalid color becomes rgb 0,0,0
self.parent.colorUpdated.emit(nick, color)
def tagmsg(self, prefix, tags, *args):
- PchumLog.info("TAGMSG: %s %s %s" % (prefix, tags, str(args)))
+ PchumLog.info("TAGMSG: {} {} {}".format(prefix, tags, str(args)))
message_tags = tags[1:].split(";")
for m in message_tags:
if m.startswith("+pesterchum"):
@@ -516,7 +516,7 @@ class PesterHandler(DefaultCommandHandler):
key, value = m.split("=")
except ValueError:
return
- PchumLog.info("Pesterchum tag: %s=%s" % (key, value))
+ PchumLog.info("Pesterchum tag: {}={}".format(key, value))
# PESTERCHUM: syntax check
if (
(value == "BEGIN")
@@ -563,7 +563,7 @@ class PesterHandler(DefaultCommandHandler):
msg = "/me" + msg[7:-1]
# CTCPs that don't need to be shown
elif msg[0] == "\x01":
- PchumLog.info('---> recv "CTCP %s :%s"' % (handle, msg[1:-1]))
+ PchumLog.info('---> recv "CTCP {} :{}"'.format(handle, msg[1:-1]))
# VERSION, return version
if msg[1:-1].startswith("VERSION"):
helpers.ctcp_reply(
@@ -609,7 +609,7 @@ class PesterHandler(DefaultCommandHandler):
if chan != "#pesterchum":
# We don't need anywhere near that much spam.
- PchumLog.info('---> recv "PRIVMSG %s :%s"' % (handle, msg))
+ PchumLog.info('---> recv "PRIVMSG {} :{}"'.format(handle, msg))
if chan == "#pesterchum":
# follow instructions
@@ -740,7 +740,7 @@ class PesterHandler(DefaultCommandHandler):
self.parent.metadata_supported = True
def cap(self, server, nick, subcommand, tag):
- PchumLog.info("CAP %s %s %s %s" % (server, nick, subcommand, tag))
+ PchumLog.info("CAP {} {} {} {}".format(server, nick, subcommand, tag))
# if tag == "message-tags":
# if subcommand == "ACK":
@@ -756,7 +756,7 @@ class PesterHandler(DefaultCommandHandler):
def quit(self, nick, reason):
handle = nick[0 : nick.find("!")]
- PchumLog.info('---> recv "QUIT %s: %s"' % (handle, reason))
+ PchumLog.info('---> recv "QUIT {}: {}"'.format(handle, reason))
if handle == self.parent.mainwindow.randhandler.randNick:
self.parent.mainwindow.randhandler.setRunning(False)
server = self.parent.mainwindow.config.server()
@@ -769,19 +769,21 @@ class PesterHandler(DefaultCommandHandler):
def kick(self, opnick, channel, handle, reason):
op = opnick[0 : opnick.find("!")]
- self.parent.userPresentUpdate.emit(handle, channel, "kick:%s:%s" % (op, reason))
+ self.parent.userPresentUpdate.emit(
+ handle, channel, "kick:{}:{}".format(op, reason)
+ )
# ok i shouldnt be overloading that but am lazy
def part(self, nick, channel, reason="nanchos"):
handle = nick[0 : nick.find("!")]
- PchumLog.info('---> recv "PART %s: %s"' % (handle, channel))
+ PchumLog.info('---> recv "PART {}: {}"'.format(handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "left")
if channel == "#pesterchum":
self.parent.moodUpdated.emit(handle, Mood("offline"))
def join(self, nick, channel):
handle = nick[0 : nick.find("!")]
- PchumLog.info('---> recv "JOIN %s: %s"' % (handle, channel))
+ PchumLog.info('---> recv "JOIN {}: {}"'.format(handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "join")
if channel == "#pesterchum":
if handle == self.parent.mainwindow.randhandler.randNick:
@@ -887,7 +889,7 @@ class PesterHandler(DefaultCommandHandler):
if l in ["+", "-"]:
cur = l
else:
- modes.append("%s%s" % (cur, l))
+ modes.append("{}{}".format(cur, l))
PchumLog.debug("handles=" + str(handles))
PchumLog.debug("enumerate(modes) = " + str(list(enumerate(modes))))
for (i, m) in enumerate(modes):
@@ -911,7 +913,7 @@ class PesterHandler(DefaultCommandHandler):
# self.parent.userPresentUpdate.emit("", channel, m+":%s" % (op))
def nick(self, oldnick, newnick, hopcount=0):
- PchumLog.info("%s, %s" % (oldnick, newnick))
+ PchumLog.info("{}, {}".format(oldnick, newnick))
# svsnick
if oldnick == self.mainwindow.profile().handle:
# Server changed our handle, svsnick?
@@ -926,7 +928,9 @@ class PesterHandler(DefaultCommandHandler):
self.parent.myHandleChanged.emit(newnick)
newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb)
self.parent.moodUpdated.emit(oldhandle, Mood("offline"))
- self.parent.userPresentUpdate.emit("%s:%s" % (oldhandle, newnick), "", "nick")
+ self.parent.userPresentUpdate.emit(
+ "{}:{}".format(oldhandle, newnick), "", "nick"
+ )
if newnick in self.mainwindow.chumList.chums:
self.getMood(newchum)
if oldhandle == self.parent.mainwindow.randhandler.randNick:
diff --git a/logviewer.py b/logviewer.py
index 737423d..38f7679 100644
--- a/logviewer.py
+++ b/logviewer.py
@@ -65,8 +65,8 @@ class PesterLogUserSelect(QtWidgets.QDialog):
instructions = QtWidgets.QLabel("Pick a memo or chumhandle:")
- if os.path.exists("%s/%s" % (self.logpath, self.handle)):
- chumMemoList = os.listdir("%s/%s/" % (self.logpath, self.handle))
+ if os.path.exists("{}/{}".format(self.logpath, self.handle)):
+ chumMemoList = os.listdir("{}/{}/".format(self.logpath, self.handle))
else:
chumMemoList = []
chumslist = config.chums()
@@ -166,17 +166,17 @@ class PesterLogViewer(QtWidgets.QDialog):
self.format = "bbcode"
if os.path.exists(
- "%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format)
+ "{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format)
):
self.logList = os.listdir(
- "%s/%s/%s/%s/" % (self.logpath, self.handle, self.chum, self.format)
+ "{}/{}/{}/{}/".format(self.logpath, self.handle, self.chum, self.format)
)
else:
self.logList = []
if (
not os.path.exists(
- "%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format)
+ "{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format)
)
or len(self.logList) == 0
):
@@ -248,7 +248,7 @@ class PesterLogViewer(QtWidgets.QDialog):
for (i, l) in enumerate(self.logList):
my = self.fileToMonthYear(l)
if my[0] != last[0]:
- child_1 = QtWidgets.QTreeWidgetItem(["%s %s" % (my[0], my[1])])
+ child_1 = QtWidgets.QTreeWidgetItem(["{} {}".format(my[0], my[1])])
# child_1.setForeground(0, blackbrush)
self.tree.addTopLevelItem(child_1)
if i == 0:
@@ -313,7 +313,7 @@ class PesterLogViewer(QtWidgets.QDialog):
.replace("[url]", "")
.replace("[/url]", "")
)
- cline = re.sub("\[color=(#.{6})]", r"", cline)
+ cline = re.sub(r"\[color=(#.{6})]", r"", cline)
self.textArea.append(convertTags(cline))
textCur = self.textArea.textCursor()
# textCur.movePosition(1)
diff --git a/memos.py b/memos.py
index 005896d..21f9f95 100644
--- a/memos.py
+++ b/memos.py
@@ -103,7 +103,7 @@ def pcfGrammar(td):
return (temporal, pcf, when)
-class TimeGrammar(object):
+class TimeGrammar:
def __init__(self, temporal, pcf, when, number="0"):
self.temporal = temporal
self.pcf = pcf
@@ -228,7 +228,7 @@ class TimeTracker(list):
class TimeInput(QtWidgets.QLineEdit):
def __init__(self, timeslider, parent):
- super(TimeInput, self).__init__(parent)
+ super().__init__(parent)
self.timeslider = timeslider
self.setText("+0:00")
self.timeslider.valueChanged[int].connect(self.setTime)
@@ -260,7 +260,7 @@ class TimeInput(QtWidgets.QLineEdit):
class TimeSlider(QtWidgets.QSlider):
def __init__(self, orientation, parent):
- super(TimeSlider, self).__init__(orientation, parent)
+ super().__init__(orientation, parent)
self.setTracking(True)
self.setMinimum(-50)
self.setMaximum(50)
@@ -278,7 +278,7 @@ class TimeSlider(QtWidgets.QSlider):
class MemoTabWindow(PesterTabWindow):
def __init__(self, mainwindow, parent=None):
- super(MemoTabWindow, self).__init__(mainwindow, parent, "memos")
+ super().__init__(mainwindow, parent, "memos")
def addChat(self, convo):
self.convos[convo.channel] = convo
@@ -302,7 +302,7 @@ _ctag_begin = re.compile(r"")
class MemoText(PesterText):
def __init__(self, theme, parent=None):
- super(MemoText, self).__init__(theme, parent)
+ super().__init__(theme, parent)
if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow
else:
@@ -1590,7 +1590,7 @@ class PesterMemo(PesterConvo):
t = self.times[h]
grammar = t.getGrammar()
allinitials.append(
- "%s%s%s" % (grammar.pcf, chum.initials(), grammar.number)
+ "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
)
self.times[h].removeTime(t.getTime())
if update == "netsplit":
@@ -1640,7 +1640,7 @@ class PesterMemo(PesterConvo):
while ttracker.getTime() is not None:
grammar = ttracker.getGrammar()
allinitials.append(
- "%s%s%s" % (grammar.pcf, chum.initials(), grammar.number)
+ "{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
)
ttracker.removeTime(ttracker.getTime())
msg = chum.memobanmsg(opchum, opgrammar, systemColor, allinitials, reason)
@@ -1873,7 +1873,7 @@ class PesterMemo(PesterConvo):
)
if ok:
self.mainwindow.kickUser.emit(
- "%s:%s" % (currentHandle, reason), self.channel
+ "{}:{}".format(currentHandle, reason), self.channel
)
@QtCore.pyqtSlot()
diff --git a/menus.py b/menus.py
index f88a476..29d5389 100644
--- a/menus.py
+++ b/menus.py
@@ -237,7 +237,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
)
if ok:
gname = str(gname)
- if re.search("[^A-Za-z0-9_\s]", gname) is not None:
+ if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@@ -1304,9 +1304,7 @@ class PesterOptions(QtWidgets.QDialog):
self.volume.valueChanged[int].connect(self.printValue)
# Disable the volume slider if we can't actually use it.
if parent.canSetVolume():
- self.currentVol = QtWidgets.QLabel(
- "{0!s}%".format(self.config.volume()), self
- )
+ self.currentVol = QtWidgets.QLabel(f"{self.config.volume()!s}%", self)
# We don't need to explicitly set this, but it helps drive the
# point home
self.volume.setEnabled(True)
diff --git a/mood.py b/mood.py
index e6de84d..749df7c 100644
--- a/mood.py
+++ b/mood.py
@@ -7,7 +7,7 @@ except ImportError:
from generic import PesterIcon
-class Mood(object):
+class Mood:
moods = [
"chummy",
"rancorous",
diff --git a/oyoyo/client.py b/oyoyo/client.py
index 0b08e29..ed5411c 100644
--- a/oyoyo/client.py
+++ b/oyoyo/client.py
@@ -246,7 +246,7 @@ class IRCClient:
passing the 'verify_hostname' parameter. The user is asked if they
want to disable it if this functions raises a certificate validation error,
in which case the function may be called again with 'verify_hostname'."""
- PchumLog.info("connecting to %s:%s" % (self.host, self.port))
+ PchumLog.info("connecting to {}:{}".format(self.host, self.port))
# Open connection
plaintext_socket = socket.create_connection((self.host, self.port))
@@ -279,7 +279,7 @@ class IRCClient:
def conn(self):
"""returns a generator object."""
try:
- buffer = bytes()
+ buffer = b""
while not self._end:
# Block for connection-killing exceptions
try:
@@ -334,7 +334,7 @@ class IRCClient:
except ssl.SSLEOFError as e:
raise e
except OSError as e:
- PchumLog.warning("conn exception %s in %s" % (e, self))
+ PchumLog.warning("conn exception {} in {}".format(e, self))
if self._end:
break
if not self.blocking and e.errno == 11:
@@ -430,7 +430,7 @@ class IRCApp:
warning: if you add a client that has blocking set to true,
timers will no longer function properly"""
- PchumLog.info("added client %s (ar=%s)" % (client, autoreconnect))
+ PchumLog.info("added client {} (ar={})".format(client, autoreconnect))
self._clients[client] = self._ClientDesc(autoreconnect=autoreconnect)
def addTimer(self, seconds, cb):
@@ -439,7 +439,7 @@ class IRCApp:
( the only advantage to these timers is they dont use threads )
"""
assert callable(cb)
- PchumLog.info("added timer to call %s in %ss" % (cb, seconds))
+ PchumLog.info("added timer to call {} in {}s".format(cb, seconds))
self._timers.append((time.time() + seconds, cb))
def run(self):
diff --git a/oyoyo/cmdhandler.py b/oyoyo/cmdhandler.py
index 3ead782..3d2c07c 100644
--- a/oyoyo/cmdhandler.py
+++ b/oyoyo/cmdhandler.py
@@ -44,7 +44,7 @@ class ProtectedCommandError(CommandError):
return 'Command "%s" is protected' % ".".join(self.cmd)
-class CommandHandler(object):
+class CommandHandler:
"""The most basic CommandHandler"""
def __init__(self, client):
@@ -91,7 +91,7 @@ class CommandHandler(object):
arguments_str = ""
for x in args:
arguments_str += str(x) + " "
- PchumLog.debug("processCommand %s(%s)" % (command, arguments_str.strip()))
+ PchumLog.debug("processCommand {}({})".format(command, arguments_str.strip()))
try:
f = self.get(command)
@@ -118,7 +118,7 @@ class CommandHandler(object):
"""The default handler for commands. Override this method to
apply custom behavior (example, printing) unhandled commands.
"""
- PchumLog.debug("unhandled command %s(%s)" % (cmd, args))
+ PchumLog.debug("unhandled command {}({})".format(cmd, args))
class DefaultCommandHandler(CommandHandler):
@@ -150,7 +150,7 @@ class DefaultBotCommandHandler(CommandHandler):
def help(self, sender, dest, arg=None):
"""list all available commands or get help on a specific command"""
- PchumLog.info("help sender=%s dest=%s arg=%s" % (sender, dest, arg))
+ PchumLog.info("help sender={} dest={} arg={}".format(sender, dest, arg))
if not arg:
commands = self.getVisibleCommands()
commands.sort()
@@ -171,7 +171,7 @@ class DefaultBotCommandHandler(CommandHandler):
if subcommands:
doc += " [sub commands: %s]" % " ".join(subcommands)
- helpers.msg(self.client, dest, "%s: %s" % (arg, doc))
+ helpers.msg(self.client, dest, "{}: {}".format(arg, doc))
class BotCommandHandler(DefaultCommandHandler):
@@ -190,7 +190,7 @@ class BotCommandHandler(DefaultCommandHandler):
and calls self.processBotCommand(cmd, sender) if its is.
"""
- PchumLog.debug("tryBotCommand('%s' '%s' '%s')" % (prefix, dest, msg))
+ PchumLog.debug("tryBotCommand('{}' '{}' '{}')".format(prefix, dest, msg))
if dest == self.client.nick:
dest = parse_nick(prefix)[0]
diff --git a/oyoyo/helpers.py b/oyoyo/helpers.py
index bfc6b93..873dd2a 100644
--- a/oyoyo/helpers.py
+++ b/oyoyo/helpers.py
@@ -46,13 +46,13 @@ def channel_list(cli):
def kick(cli, handle, channel, reason=""):
- cli.send("KICK %s %s %s" % (channel, handle, reason))
+ cli.send("KICK {} {} {}".format(channel, handle, reason))
def mode(cli, channel, mode, options=None):
PchumLog.debug("mode = " + str(mode))
PchumLog.debug("options = " + str(options))
- cmd = "MODE %s %s" % (channel, mode)
+ cmd = "MODE {} {}".format(channel, mode)
if options:
cmd += " %s" % (options)
cli.send(cmd)
@@ -63,11 +63,11 @@ def ctcp(cli, handle, cmd, msg=""):
if msg == "":
cli.send("PRIVMSG", handle, "\x01%s\x01" % (cmd))
else:
- cli.send("PRIVMSG", handle, "\x01%s %s\x01" % (cmd, msg))
+ cli.send("PRIVMSG", handle, "\x01{} {}\x01".format(cmd, msg))
def ctcp_reply(cli, handle, cmd, msg=""):
- notice(cli, str(handle), "\x01%s %s\x01" % (cmd.upper(), msg))
+ notice(cli, str(handle), "\x01{} {}\x01".format(cmd.upper(), msg))
def metadata(cli, target, subcommand, *params):
@@ -115,22 +115,28 @@ def identify(cli, passwd, authuser="NickServ"):
def quit(cli, msg):
cli.send("QUIT %s" % (msg))
+
def nick(cli, nick):
- cli.seld("NICK", nick)
+ cli.send("NICK", nick)
+
def user(cli, username, realname):
cli.send("USER", username, "0", "*", ":" + realname)
+
def join(cli, channel):
"""Protocol potentially allows multiple channels or keys."""
cli.send("JOIN", channel)
+
def part(cli, channel):
cli.send("PART", channel)
+
def notice(cli, target, text):
cli.send("NOTICE", target, text)
+
def invite(cli, nick, channel):
cli.send("INVITE", nick, channel)
diff --git a/oyoyo/services.py b/oyoyo/services.py
index c0c4848..7c58e50 100644
--- a/oyoyo/services.py
+++ b/oyoyo/services.py
@@ -111,14 +111,14 @@ def _addServ(serv, funcs, prefix=""):
setattr(serv, t, simplecmd(t.upper()))
-class NickServ(object):
+class NickServ:
def __init__(self, nick="NickServ"):
self.name = nick
_addServ(self, _nickservfuncs)
_addServ(self, _nickservsetfuncs, "set")
-class ChanServ(object):
+class ChanServ:
def __init__(self, nick="ChanServ"):
self.name = nick
_addServ(self, _chanservfuncs)
diff --git a/parsetools.py b/parsetools.py
index bbc264f..59617f6 100644
--- a/parsetools.py
+++ b/parsetools.py
@@ -115,7 +115,7 @@ class colorBegin(lexercon.Chunk):
return "[color=%s]" % (qc.name())
elif format == "ctag":
(r, g, b, a) = qc.getRgb()
- return "" % (r, g, b)
+ return "".format(r, g, b)
class colorEnd(lexercon.Chunk):
@@ -171,7 +171,7 @@ class hyperlink(lexercon.Chunk):
def convert(self, format):
if format == "html":
- return "%s" % (self.string, self.string)
+ return "{}".format(self.string, self.string)
elif format == "bbcode":
return "[url]%s[/url]" % (self.string)
else:
@@ -211,7 +211,9 @@ class memolex(lexercon.Chunk):
def convert(self, format):
if format == "html":
- return "%s%s" % (self.space, self.channel, self.channel)
+ return "{}{}".format(
+ self.space, self.channel, self.channel
+ )
else:
return self.string
@@ -224,7 +226,7 @@ class chumhandlelex(lexercon.Chunk):
def convert(self, format):
if format == "html":
- return "%s%s" % (self.space, self.handle, self.handle)
+ return "{}{}".format(self.space, self.handle, self.handle)
else:
return self.string
@@ -235,7 +237,7 @@ class smiley(lexercon.Chunk):
def convert(self, format):
if format == "html":
- return "" % (
+ return "".format(
smiledict[self.string],
self.string,
self.string,
@@ -461,7 +463,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
while len(lexed) > 0:
rounds += 1
if debug:
- PchumLog.info("[Starting round {}...]".format(rounds))
+ PchumLog.info(f"[Starting round {rounds}...]")
msg = lexed.popleft()
msglen = 0
is_text = False
@@ -502,9 +504,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# instead?
subround += 1
if debug:
- PchumLog.info(
- "[Splitting round {}-{}...]".format(rounds, subround)
- )
+ PchumLog.info(f"[Splitting round {rounds}-{subround}...]")
point = msg.rfind(" ", 0, lenl)
if point < 0:
# No spaces to break on...ugh. Break at the last space
@@ -517,12 +517,12 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# Remove what we just added.
msg = msg[point:]
if debug:
- PchumLog.info("msg = {!r}".format(msg))
+ PchumLog.info(f"msg = {msg!r}")
else:
# Catch the remainder.
stack.append(msg)
if debug:
- PchumLog.info("msg caught; stack = {!r}".format(stack))
+ PchumLog.info(f"msg caught; stack = {stack!r}")
# Done processing. Pluck out the first portion so we can
# continue processing, clean it up a bit, then add the rest to
# our waiting list.
@@ -564,7 +564,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working.extend([cte] * len(open_ctags))
if debug:
print(
- "\tRound {0} linebreak: Added {1} closing ctags".format(
+ "\tRound {} linebreak: Added {} closing ctags".format(
rounds, len(open_ctags)
)
)
@@ -573,7 +573,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = "".join(kxpclexer.list_convert(working))
if debug:
print(
- "\tRound {0} add: len == {1} (of {2})".format(
+ "\tRound {} add: len == {} (of {})".format(
rounds, len(working), maxlen
)
)
@@ -591,7 +591,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# We have more to go.
# Reset working, starting it with the unclosed ctags.
if debug:
- print("\tRound {0}: More to lex".format(rounds))
+ print(f"\tRound {rounds}: More to lex")
working = open_ctags[:]
# Calculate the length of the starting tags, add it before
# anything else.
@@ -606,7 +606,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
if debug or True:
# This probably shouldn't happen, and if it does, I want to
# know if it *works* properly.
- print("\tRound {0}: No more to lex".format(rounds))
+ print(f"\tRound {rounds}: No more to lex")
# Clean up, just in case.
working = []
open_ctags = []
@@ -655,7 +655,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = kxpclexer.list_convert(working)
if len(working) > 0:
if debug:
- print("Adding end trails: {!r}".format(working))
+ print(f"Adding end trails: {working!r}")
working = "".join(working)
output.append(working)
@@ -722,7 +722,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
# Determine if the line actually *is* OOC.
if is_ooc and not oocDetected:
# If we're supposed to be OOC, apply it artificially.
- msg = "(( {} ))".format(msg)
+ msg = f"(( {msg} ))"
# Also, quirk stuff.
should_quirk = ctx.applyquirks
else:
@@ -861,7 +861,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
clientMsg, colorcmd, grammar.pcf, initials, grammar.number
)
# Not sure if this needs a space at the end...?
- serverMsg = "{2}: {0}".format(serverMsg, colorcmd, initials)
+ serverMsg = f"{initials}: {serverMsg}"
ctx.addMessage(clientMsg, True)
if flavor != "menus":
@@ -935,7 +935,7 @@ def nonerep(text):
return text
-class parseLeaf(object):
+class parseLeaf:
def __init__(self, function, parent):
self.nodes = []
self.function = function
@@ -957,7 +957,7 @@ class parseLeaf(object):
return out
-class backreference(object):
+class backreference:
def __init__(self, number):
self.number = number
@@ -1071,7 +1071,7 @@ smiledict = {
":honk:": "honk.png",
}
-reverse_smiley = dict((v, k) for k, v in smiledict.items())
+reverse_smiley = {v: k for k, v in smiledict.items()}
_smilere = re.compile("|".join(list(smiledict.keys())))
diff --git a/pesterchum.py b/pesterchum.py
index 1197181..94e33ab 100755
--- a/pesterchum.py
+++ b/pesterchum.py
@@ -210,7 +210,7 @@ except ImportError:
)
-class waitingMessageHolder(object):
+class waitingMessageHolder:
def __init__(self, mainwindow, **msgfuncs):
self.mainwindow = mainwindow
self.funcs = msgfuncs
@@ -246,14 +246,14 @@ class waitingMessageHolder(object):
class chumListing(QtWidgets.QTreeWidgetItem):
def __init__(self, chum, window):
- super(chumListing, self).__init__([chum.handle])
+ super().__init__([chum.handle])
self.mainwindow = window
self.chum = chum
self.handle = chum.handle
self.setMood(Mood("offline"))
self.status = None
self.setToolTip(
- 0, "%s: %s" % (chum.handle, window.chumdb.getNotes(chum.handle))
+ 0, "{}: {}".format(chum.handle, window.chumdb.getNotes(chum.handle))
)
def setMood(self, mood):
@@ -330,11 +330,9 @@ class chumListing(QtWidgets.QTreeWidgetItem):
0,
QtGui.QBrush(
QtGui.QColor(
- (
- self.mainwindow.theme["main/chums/moods"][self.mood.name()][
- "color"
- ]
- )
+ self.mainwindow.theme["main/chums/moods"][self.mood.name()][
+ "color"
+ ]
)
),
)
@@ -342,9 +340,7 @@ class chumListing(QtWidgets.QTreeWidgetItem):
self.setForeground(
0,
QtGui.QBrush(
- QtGui.QColor(
- (self.mainwindow.theme["main/chums/moods/chummy/color"])
- )
+ QtGui.QColor(self.mainwindow.theme["main/chums/moods/chummy/color"])
),
)
@@ -379,7 +375,7 @@ class chumArea(RightClickTree):
# This is the class that controls the actual main chumlist, I think.
# Looking into how the groups work might be wise.
def __init__(self, chums, parent=None):
- super(chumArea, self).__init__(parent)
+ super().__init__(parent)
self.notify = False
QtCore.QTimer.singleShot(30000, self.beginNotify)
self.mainwindow = parent
@@ -1061,7 +1057,7 @@ class chumArea(RightClickTree):
if ok:
notes = str(notes)
self.mainwindow.chumdb.setNotes(currentChum.handle, notes)
- currentChum.setToolTip(0, "%s: %s" % (currentChum.handle, notes))
+ currentChum.setToolTip(0, "{}: {}".format(currentChum.handle, notes))
@QtCore.pyqtSlot()
def renameGroup(self):
@@ -1073,7 +1069,7 @@ class chumArea(RightClickTree):
)
if ok:
gname = str(gname)
- if re.search("[^A-Za-z0-9_\s]", gname) is not None:
+ if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setStyleSheet(
"QMessageBox{ %s }"
@@ -1210,7 +1206,7 @@ class trollSlum(chumArea):
class TrollSlumWindow(QtWidgets.QFrame):
def __init__(self, trolls, mainwindow, parent=None):
- super(TrollSlumWindow, self).__init__(parent)
+ super().__init__(parent)
self.mainwindow = mainwindow
theme = self.mainwindow.theme
self.slumlabel = QtWidgets.QLabel(self)
@@ -1298,7 +1294,7 @@ class PesterWindow(MovingWindow):
sendMessage = QtCore.pyqtSignal("QString", "QString")
def __init__(self, options, parent=None, app=None):
- super(PesterWindow, self).__init__(
+ super().__init__(
None,
(
QtCore.Qt.WindowType.CustomizeWindowHint
@@ -1357,7 +1353,7 @@ class PesterWindow(MovingWindow):
msgBox.setText(
"A profile error occured, "
"trying to switch to default pesterClient profile."
- "
%s<\h3><\html>" % e
+ r"
%s<\h3><\html>" % e
)
PchumLog.critical(e)
msgBox.exec()
@@ -1917,7 +1913,7 @@ class PesterWindow(MovingWindow):
msg = addTimeInitial(msg, memo.times[handle].getGrammar())
if handle == "ChanServ":
systemColor = QtGui.QColor(self.theme["memos/systemMsgColor"])
- msg = "%s" % (systemColor.name(), msg)
+ msg = "{}".format(systemColor.name(), msg)
memo.addMessage(msg, handle)
mentioned = False
m = convertTags(msg, "text")
@@ -2242,7 +2238,7 @@ class PesterWindow(MovingWindow):
if hasattr(self, "moods"):
self.moods.removeButtons()
mood_list = theme["main/moods"]
- mood_list = [dict([(str(k), v) for (k, v) in d.items()]) for d in mood_list]
+ mood_list = [{str(k): v for (k, v) in d.items()} for d in mood_list]
self.moods = PesterMoodHandler(
self, *[PesterMoodButton(self, **d) for d in mood_list]
)
@@ -2391,7 +2387,7 @@ class PesterWindow(MovingWindow):
QtCore.QUrl.fromLocalFile("themes/honk.wav")
)
except Exception as err:
- PchumLog.error("Warning: Error loading sounds! ({0!r})".format(err))
+ PchumLog.error(f"Warning: Error loading sounds! ({err!r})")
self.alarm = NoneSound()
self.memosound = NoneSound()
self.namesound = NoneSound()
@@ -2419,7 +2415,7 @@ class PesterWindow(MovingWindow):
if self.sound_type == QtMultimedia.QSoundEffect:
sound.setVolume(vol)
except Exception as err:
- PchumLog.warning("Couldn't set volume: {}".format(err))
+ PchumLog.warning(f"Couldn't set volume: {err}")
def canSetVolume(self):
"""Returns the state of volume setting capabilities."""
@@ -2793,7 +2789,7 @@ class PesterWindow(MovingWindow):
errormsg.showMessage("THIS IS NOT A VALID CHUMTAG!")
self.addchumdialog = None
return
- if re.search("[^A-Za-z0-9_\s]", group) is not None:
+ if re.search(r"[^A-Za-z0-9_\s]", group) is not None:
errormsg = QtWidgets.QErrorMessage(self)
errormsg.showMessage("THIS IS NOT A VALID GROUP NAME")
self.addchumdialog = None
@@ -2817,7 +2813,7 @@ class PesterWindow(MovingWindow):
"Enter the reason you are reporting this user (optional):",
)
if ok:
- self.sendMessage.emit("REPORT %s %s" % (handle, reason), "calSprite")
+ self.sendMessage.emit("REPORT {} {}".format(handle, reason), "calSprite")
@QtCore.pyqtSlot(QString)
def blockChum(self, handle):
@@ -2946,7 +2942,7 @@ class PesterWindow(MovingWindow):
f = QtWidgets.QFileDialog.getOpenFileName(self)[0]
if f == "":
return
- fp = open(f, "r")
+ fp = open(f)
regexp_state = None
for l in fp:
# import chumlist
@@ -3139,7 +3135,7 @@ class PesterWindow(MovingWindow):
)
if ok:
gname = str(gname)
- if re.search("[^A-Za-z0-9_\s]", gname) is not None:
+ if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@@ -3500,7 +3496,7 @@ class PesterWindow(MovingWindow):
"
"
"If you got this message at launch you may want to "
"change your default profile."
- "
%s<\h3><\html>"
+ r"
%s<\h3><\html>"
% (self.profiledir, self.profiledir, handle, e)
)
@@ -3512,7 +3508,7 @@ class PesterWindow(MovingWindow):
"file exists."
"
If you got this message at launch you may "
"want to change your default profile."
- "
%s<\h3><\html>" % e
+ r"
%s<\h3><\html>" % e
)
PchumLog.critical(e)
msgBox.setText(msg)
@@ -3769,7 +3765,7 @@ class PesterWindow(MovingWindow):
self.chooseServer()
return 1
- with open(_datadir + "serverlist.json", "r") as server_file:
+ with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_list_obj = json.loads(read_file)
@@ -3826,7 +3822,7 @@ class PesterWindow(MovingWindow):
def removeServer(self):
server_list_items = []
try:
- with open(_datadir + "serverlist.json", "r") as server_file:
+ with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_list_obj = json.loads(read_file)
@@ -3928,7 +3924,7 @@ class PesterWindow(MovingWindow):
# Read servers.
server_list_items = []
try:
- with open(_datadir + "serverlist.json", "r") as server_file:
+ with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@@ -3988,7 +3984,7 @@ class PesterWindow(MovingWindow):
else:
PchumLog.info(self.serverBox.currentText() + " chosen.")
- with open(_datadir + "serverlist.json", "r") as server_file:
+ with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@@ -4031,7 +4027,7 @@ class PesterWindow(MovingWindow):
# Read servers.
server_list_items = []
try:
- with open(_datadir + "serverlist.json", "r") as server_file:
+ with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@@ -4103,7 +4099,7 @@ class PesterWindow(MovingWindow):
msgbox.setIcon(QtWidgets.QMessageBox.Icon.Warning)
msgbox.setText("Server certificate validation failed")
msgbox.setInformativeText(
- 'Reason: "%s (%s)"' % (e.verify_message, e.verify_code)
+ 'Reason: "{} ({})"'.format(e.verify_message, e.verify_code)
+ "\n\nConnect anyway?"
)
msgbox.setStandardButtons(
@@ -4154,7 +4150,7 @@ class PesterWindow(MovingWindow):
class PesterTray(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, mainwindow, parent):
- super(PesterTray, self).__init__(icon, parent)
+ super().__init__(icon, parent)
self.mainwindow = mainwindow
@QtCore.pyqtSlot(int)
@@ -4171,7 +4167,7 @@ class PesterTray(QtWidgets.QSystemTrayIcon):
class MainProgram(QtCore.QObject):
def __init__(self):
- super(MainProgram, self).__init__()
+ super().__init__()
_oldhook = sys.excepthook
sys.excepthook = self.uncaughtException
@@ -4195,8 +4191,8 @@ class MainProgram(QtCore.QObject):
windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid)
except Exception as err:
# Log, but otherwise ignore any exceptions.
- PchumLog.error("Failed to set AppUserModel ID: {0}".format(err))
- PchumLog.error("Attempted to set as {0!r}.".format(wid))
+ PchumLog.error(f"Failed to set AppUserModel ID: {err}")
+ PchumLog.error(f"Attempted to set as {wid!r}.")
# Back to our scheduled program.
self.app = QtWidgets.QApplication(sys.argv)
@@ -4563,7 +4559,7 @@ class MainProgram(QtCore.QObject):
# Show error to end user and log.
try:
# Log to log file
- PchumLog.error("%s, %s" % (exc, value))
+ PchumLog.error("{}, {}".format(exc, value))
# Try to write to separate logfile
try:
diff --git a/pnc/dep/attrdict.py b/pnc/dep/attrdict.py
index 6b29762..dea6063 100644
--- a/pnc/dep/attrdict.py
+++ b/pnc/dep/attrdict.py
@@ -1,4 +1,3 @@
-# -*- coding=UTF-8; tab-width: 4 -*-
# Heavily modified version of the code featured at the given link
## {{{ http://code.activestate.com/recipes/473786/ (r1)
class AttrDict(dict):
@@ -11,7 +10,7 @@ class AttrDict(dict):
Overload _is_reserved if you want to change this."""
def __init__(self, init={}):
- super(AttrDict, self).__init__(init)
+ super().__init__(init)
def __getstate__(self):
return list(self.__dict__.items())
@@ -21,16 +20,16 @@ class AttrDict(dict):
self.__dict__[key] = val
def __repr__(self):
- return "{0}({1})".format(type(self).__name__, super(AttrDict, self).__repr__())
+ return f"{type(self).__name__}({super().__repr__()})"
def __setitem__(self, name, value):
- return super(AttrDict, self).__setitem__(name, value)
+ return super().__setitem__(name, value)
def __getitem__(self, name):
- return super(AttrDict, self).__getitem__(name)
+ return super().__getitem__(name)
def __delitem__(self, name):
- return super(AttrDict, self).__delitem__(name)
+ return super().__delitem__(name)
def __getattr__(self, name):
# NOTE: __getattr__ is called if the code has already failed to access
@@ -50,7 +49,7 @@ class AttrDict(dict):
# Raising KeyError here will confuse __deepcopy__, so don't do
# that.
# Throw a custom error.
- raise AttributeError("No key/attr {0!r}".format(name))
+ raise AttributeError(f"No key/attr {name!r}")
return result
def __setattr__(self, name, value):
@@ -68,7 +67,7 @@ class AttrDict(dict):
# in this particular function?...
return object.__setattr__(self, name, value)
else:
- return super(AttrDict, self).__setitem__(name, value)
+ return super().__setitem__(name, value)
def __delattr__(self, name):
# We very *specifically* use self.__dict__ here, because we couldn't
@@ -106,10 +105,10 @@ class DefAttrDict(AttrDict):
def __init__(self, default_factory=None, *args, **kwargs):
self.default_factory = default_factory
- super(DefAttrDict, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def __repr__(self):
- return "{0}({1!r}, {2})".format(
+ return "{}({!r}, {})".format(
type(self).__name__,
self.default_factory,
# We skip normal processing here, since AttrDict provides basic
@@ -119,7 +118,7 @@ class DefAttrDict(AttrDict):
def __getitem__(self, name):
try:
- result = super(DefAttrDict, self).__getitem__(name)
+ result = super().__getitem__(name)
except KeyError:
result = None
if self.default_factory is not None:
@@ -129,7 +128,7 @@ class DefAttrDict(AttrDict):
def __getattr__(self, name):
try:
- result = super(DefAttrDict, self).__getattr__(name)
+ result = super().__getattr__(name)
except AttributeError:
# Detect special/reserved names.
if self._is_reserved(name):
diff --git a/pnc/lexercon.py b/pnc/lexercon.py
index 8337404..3c721c1 100644
--- a/pnc/lexercon.py
+++ b/pnc/lexercon.py
@@ -1,6 +1,3 @@
-# -*- coding=UTF-8; tab-width: 4 -*-
-
-
from .unicolor import Color
import re
@@ -20,7 +17,7 @@ except NameError:
# function appropriate to the given format - e.g. CTag.convert_pchum.
-class Lexeme(object):
+class Lexeme:
def __init__(self, string, origin):
# The 'string' property is just what it came from; the original
# representation. It doesn't have to be used, and honestly probably
@@ -104,7 +101,7 @@ class CTag(Specifier):
sets_color = True
def __init__(self, string, origin, color):
- super(CTag, self).__init__(string, origin)
+ super().__init__(string, origin)
# So we can also have None
if isinstance(color, tuple):
if len(color) < 2:
@@ -256,7 +253,7 @@ class SpecifierEnd(CTagEnd, FTagEnd):
# .sets_color to False
-class Lexer(object):
+class Lexer:
# Subclasses need to supply a ref themselves
ref = None
compress_tags = False
diff --git a/pnc/unicolor.py b/pnc/unicolor.py
index 7a8208b..95dbe80 100644
--- a/pnc/unicolor.py
+++ b/pnc/unicolor.py
@@ -1,6 +1,3 @@
-# -*- coding=UTF-8; tab-width: 4 -*-
-
-
__all__ = ["Color"]
# karxi: Copied from my old Textsub script. Please forgive the mess, and keep
@@ -26,7 +23,7 @@ else:
LabTuple = collections.namedtuple("LabTuple", ["L", "a", "b"])
-class Color(object):
+class Color:
# The threshold at which to consider two colors noticeably different, even
# if only barely
jnd = 2.3
@@ -145,7 +142,7 @@ class Color(object):
def __repr__(self):
##return "%s(%r)" % (type(self).__name__, str(self))
- return "%s(%r)" % (type(self).__name__, self.reduce_hexstr(self.hexstr))
+ return "{}({!r})".format(type(self).__name__, self.reduce_hexstr(self.hexstr))
def __str__(self):
##return self.reduce_hexstr(self.hexstr)
@@ -158,8 +155,7 @@ class Color(object):
def __iter__(self):
targs = (self.red, self.green, self.blue)
- for t in targs:
- yield t
+ yield from targs
# If we got here, we're out of attributes to provide
raise StopIteration
diff --git a/profile.py b/profile.py
index 8c264bc..d5502ed 100644
--- a/profile.py
+++ b/profile.py
@@ -25,7 +25,7 @@ _datadir = ostools.getDataDir()
PchumLog = logging.getLogger("pchumLogger")
-class PesterLog(object):
+class PesterLog:
def __init__(self, handle, parent=None):
global _datadir
self.parent = parent
@@ -66,10 +66,12 @@ class PesterLog(object):
self.convos[handle] = {}
for (format, t) in modes.items():
if not os.path.exists(
- "%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)
+ "{}/{}/{}/{}".format(self.logpath, self.handle, handle, format)
):
os.makedirs(
- "%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)
+ "{}/{}/{}/{}".format(
+ self.logpath, self.handle, handle, format
+ )
)
fp = codecs.open(
"%s/%s/%s/%s/%s.%s.txt"
@@ -94,7 +96,7 @@ class PesterLog(object):
# for (format, t) in modes.items():
# self.finish(handle)
- except (IOError, OSError, KeyError, IndexError, ValueError) as e:
+ except (OSError, KeyError, IndexError, ValueError) as e:
# Catching this exception does not stop pchum from dying if we run out of file handles 3
PchumLog.critical(e)
errmsg = QtWidgets.QMessageBox()
@@ -125,7 +127,7 @@ class PesterLog(object):
f.close()
-class userConfig(object):
+class userConfig:
def __init__(self, parent):
self.parent = parent
# Use for bit flag log setting
@@ -184,9 +186,9 @@ with a backup from: %s
"
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
try:
- with open("%s/groups.js" % (self.logpath), "r") as fp:
+ with open("%s/groups.js" % (self.logpath)) as fp:
self.groups = json.load(fp)
- except (IOError, ValueError):
+ except (OSError, ValueError):
self.groups = {}
with open("%s/groups.js" % (self.logpath), "w") as fp:
json.dump(self.groups, fp)
@@ -442,7 +444,7 @@ with a backup from: %s