Skip to content

Commit 13fe7fb

Browse files
committed
Better type hinting, fstrings in threads and mainapp
1 parent 2adbf04 commit 13fe7fb

8 files changed

+96
-91
lines changed

src/constants.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import os
88
from queue import Queue
99

10-
wqueue = Queue() # type: Queue[str]
10+
wqueue: Queue[str] = Queue()
1111

1212
APPDATA_DIRNAME = ".PET4L-DATA"
1313

@@ -21,7 +21,7 @@
2121
TESTNET_MAGIC_BYTE = 139
2222
TESTNET_STAKE_MAGIC_BYTE = 73
2323
DEFAULT_PROTOCOL_VERSION = 70915
24-
MINIMUM_FEE = 0.0001 # minimum PIV/kB
24+
MINIMUM_FEE = 0.0001 # minimum PIV/kB
2525
SECONDS_IN_2_MONTHS = 60 * 24 * 60 * 60
2626
MAX_INPUTS_NO_WARNING = 75
2727
starting_width = 1033
@@ -50,8 +50,8 @@
5050
trusted_RPC_Servers = [
5151
["https", "lithuania.fuzzbawls.pw:8080", "spmtUser", "WUss6sr8956S5Paex254"],
5252
["https", "latvia.fuzzbawls.pw:8080", "spmtUser", "8X88u7TuefPm7mQaJY52"],
53-
["https", "charlotte.fuzzbawls.pw:8080", "spmtUser", "ZyD936tm9dvqmMP8A777"]]
54-
53+
["https", "charlotte.fuzzbawls.pw:8080", "spmtUser", "ZyD936tm9dvqmMP8A777"]
54+
]
5555

5656
HW_devices = [
5757
# (model name, api index)

src/mainApp.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
from misc import printDbg, initLogs, saveCacheSettings, readCacheSettings, getVersion
1818
from mainWindow import MainWindow
1919
from constants import user_dir, SECONDS_IN_2_MONTHS
20-
from qt.dlg_configureRPCservers import ConfigureRPCservers_dlg
21-
from qt.dlg_signmessage import SignMessage_dlg
20+
from qt.dlg_configureRPCservers import ConfigureRPCserversDlg
21+
from qt.dlg_signmessage import SignMessageDlg
2222

2323

2424
class ServiceExit(Exception):
@@ -30,7 +30,7 @@ class ServiceExit(Exception):
3030

3131

3232
def service_shutdown(signum, frame):
33-
print('Caught signal %d' % signum)
33+
print(f'Caught signal {signum}')
3434
raise ServiceExit
3535

3636

@@ -54,7 +54,7 @@ def __init__(self, imgDir, app, start_args):
5454

5555
# Get version and title
5656
self.version = getVersion()
57-
self.title = 'PET4L - PIVX Emergency Tool For Ledger - v.%s-%s' % (self.version['number'], self.version['tag'])
57+
self.title = f'PET4L - PIVX Emergency Tool For Ledger - v.{self.version["number"]}-{self.version["tag"]}'
5858

5959
# Open database
6060
self.db = Database(self)
@@ -107,7 +107,7 @@ def initUI(self, imgDir):
107107
self.show()
108108
self.activateWindow()
109109

110-
def closeEvent(self, *args, **kwargs):
110+
def closeEvent(self, event):
111111
# Terminate the running threads.
112112
# Set the shutdown flag on each thread to trigger a clean shutdown of each thread.
113113
self.mainWindow.myRpcWd.shutdown_flag.set()
@@ -133,16 +133,16 @@ def closeEvent(self, *args, **kwargs):
133133

134134
# Adios
135135
print("Bye Bye.")
136-
return QMainWindow.closeEvent(self, *args, **kwargs)
136+
return super().closeEvent(event)
137137

138138
def onEditRPCServer(self):
139139
# Create Dialog
140-
ui = ConfigureRPCservers_dlg(self)
140+
ui = ConfigureRPCserversDlg(self)
141141
if ui.exec():
142142
printDbg("Configuring RPC Servers...")
143143

144144
def onSignVerifyMessage(self):
145145
# Create Dialog
146-
ui = SignMessage_dlg(self.mainWindow)
146+
ui = SignMessageDlg(self.mainWindow)
147147
if ui.exec():
148148
printDbg("Sign/Verify message...")

src/mainWindow.py

+19-21
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from PyQt5.QtCore import pyqtSignal, Qt, QThread
1414
from PyQt5.QtGui import QPixmap, QColor, QPalette, QTextCursor, QFont, QIcon
1515
from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QGroupBox, QVBoxLayout, \
16-
QFileDialog, QTextEdit, QTabWidget, QLabel, QSplitter
16+
QFileDialog, QTextEdit, QTabWidget, QLabel, QSplitter, QAction, QMenuBar
1717

1818
from apiClient import ApiClient
1919
from constants import starting_height, DefaultCache, wqueue
@@ -41,9 +41,8 @@ class MainWindow(QWidget):
4141
# signal: UTXO list loading percent (emitted by load_utxos_thread in tabRewards)
4242
sig_UTXOsLoading = pyqtSignal(int)
4343

44-
4544
def __init__(self, parent, imgDir):
46-
super(QWidget, self).__init__(parent)
45+
super().__init__(parent)
4746
self.parent = parent
4847
self.imgDir = imgDir
4948
self.runInThread = ThreadFuns.runInThread
@@ -79,7 +78,7 @@ def __init__(self, parent, imgDir):
7978
self.hwdevice = HWdevice(self)
8079

8180
# -- init Api Client
82-
self.apiClient = ApiClient(self.isTestnetRPC)
81+
self.apiClient = ApiClient(self) # Pass 'self' as main_wnd reference
8382

8483
# -- Create Queue to redirect stdout
8584
self.queue = wqueue
@@ -257,15 +256,15 @@ def checkVersion(self, ctrl):
257256
(remote_version[0] == local_version[0] and remote_version[1] > local_version[1]) or \
258257
(remote_version[0] == local_version[0] and remote_version[1] == local_version[1] and remote_version[2] >
259258
local_version[2]):
260-
self.versionMess = '<b style="color:red">New Version Available:</b> %s ' % (self.gitVersion)
259+
self.versionMess = f'<b style="color:red">New Version Available:</b> {self.gitVersion} '
261260
self.versionMess += '(<a href="https://github.com/PIVX-Project/PET4L/releases/">download</a>)'
262261
else:
263262
self.versionMess = "You have the latest version of PET4L"
264263

265264
def updateVersion(self):
266265
if self.versionMess is not None:
267266
self.versionLabel.setText(self.versionMess)
268-
printOK("Remote version: %s" % str(self.gitVersion))
267+
printOK(f"Remote version: {self.gitVersion}")
269268

270269
def onChangeSelectedHW(self, i):
271270
# Clear status
@@ -288,14 +287,13 @@ def onSaveConsole(self):
288287
timestamp = strftime('%Y-%m-%d_%H-%M-%S', gmtime(now()))
289288
options = QFileDialog.Options()
290289
options |= QFileDialog.DontUseNativeDialog
291-
fileName, _ = QFileDialog.getSaveFileName(self, "Save Logs to file", "PET4L_Logs_%s.txt" % timestamp, "All Files (*);; Text Files (*.txt)", options=options)
290+
fileName, _ = QFileDialog.getSaveFileName(self, f"Save Logs to file PET4L_Logs_{timestamp}.txt", "All Files (*);; Text Files (*.txt)", options=options)
292291
try:
293292
if fileName:
294-
printOK("Saving logs to %s" % fileName)
295-
log_file = open(fileName, 'w+', encoding="utf-8")
296-
log_text = self.consoleArea.toPlainText()
297-
log_file.write(log_text)
298-
log_file.close()
293+
printOK(f"Saving logs to {fileName}")
294+
with open(fileName, 'w+', encoding="utf-8") as log_file:
295+
log_text = self.consoleArea.toPlainText()
296+
log_file.write(log_text)
299297

300298
except Exception as e:
301299
err_msg = "error writing Log file"
@@ -315,14 +313,14 @@ def onToggleConsole(self):
315313

316314
def showHWstatus(self):
317315
self.updateHWleds()
318-
myPopUp_sb(self, "info", 'PET4L - hw check', "%s" % self.hwStatusMess)
316+
myPopUp_sb(self, "info", 'PET4L - hw check', f"{self.hwStatusMess}")
319317

320318
def showRPCstatus(self, server_index, fDebug):
321319
# Update displayed status only if selected server is not changed
322320
if server_index == self.header.rpcClientsBox.currentIndex():
323321
self.updateRPCled(fDebug)
324322
if fDebug:
325-
myPopUp_sb(self, "info", 'PET4L - rpc check', "%s" % self.rpcStatusMess)
323+
myPopUp_sb(self, "info", 'PET4L - rpc check', f"{self.rpcStatusMess}")
326324

327325
def updateHWleds(self):
328326
if self.hwStatus == 1:
@@ -342,7 +340,7 @@ def updateHWstatus(self, ctrl):
342340
printDbg(str(e))
343341
pass
344342

345-
printDbg("status:%s - mess: %s" % (self.hwStatus, self.hwStatusMess))
343+
printDbg(f"status:{self.hwStatus} - mess: {self.hwStatusMess}")
346344

347345
def updateLastBlockLabel(self):
348346
text = '--'
@@ -370,9 +368,9 @@ def updateLastBlockPing(self):
370368
color = "green"
371369
self.header.lastPingIcon.setPixmap(self.connGreen_icon)
372370
if self.rpcResponseTime is not None:
373-
self.header.responseTimeLabel.setText("%.3f" % self.rpcResponseTime)
374-
self.header.responseTimeLabel.setStyleSheet("color: %s" % color)
375-
self.header.lastPingIcon.setStyleSheet("color: %s" % color)
371+
self.header.responseTimeLabel.setText(f"{self.rpcResponseTime:.3f}")
372+
self.header.responseTimeLabel.setStyleSheet(f"color: {color}")
373+
self.header.lastPingIcon.setStyleSheet(f"color: {color}")
376374

377375
def updateRPCled(self, fDebug=False):
378376
if self.rpcConnected:
@@ -403,7 +401,7 @@ def updateRPClist(self):
403401
# Add public servers (italics)
404402
italicsFont = QFont("Times", italic=True)
405403
for s in public_servers:
406-
url = s["protocol"] + "://" + s["host"].split(':')[0]
404+
url = f"{s['protocol']}://{s['host'].split(':')[0]}"
407405
self.header.rpcClientsBox.addItem(url, s)
408406
self.header.rpcClientsBox.setItemData(self.getServerListIndex(s), italicsFont, Qt.FontRole)
409407
# Add Local Wallet (bold)
@@ -413,7 +411,7 @@ def updateRPClist(self):
413411
self.header.rpcClientsBox.setItemData(self.getServerListIndex(custom_servers[0]), boldFont, Qt.FontRole)
414412
# Add custom servers
415413
for s in custom_servers[1:]:
416-
url = s["protocol"] + "://" + s["host"].split(':')[0]
414+
url = f"{s['protocol']}://{s['host'].split(':')[0]}"
417415
self.header.rpcClientsBox.addItem(url, s)
418416
# reset index
419417
if self.parent.cache['selectedRPC_index'] >= self.header.rpcClientsBox.count():
@@ -428,7 +426,7 @@ def updateRPClist(self):
428426
def updateRPCstatus(self, ctrl, fDebug=False):
429427
rpc_index, rpc_protocol, rpc_host, rpc_user, rpc_password = self.getRPCserver()
430428
if fDebug:
431-
printDbg("Trying to connect to RPC %s://%s..." % (rpc_protocol, rpc_host))
429+
printDbg(f"Trying to connect to RPC {rpc_protocol}://{rpc_host}...")
432430

433431
try:
434432
rpcClient = RpcClient(rpc_protocol, rpc_host, rpc_user, rpc_password)

src/qt/guiHeader.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
class GuiHeader(QWidget):
1414
def __init__(self, caller, *args, **kwargs):
15-
QWidget.__init__(self)
15+
super().__init__(*args, **kwargs)
1616
layout = QHBoxLayout()
1717
layout.setContentsMargins(0, 0, 0, 0)
1818
# --- 1) Check Box
@@ -28,7 +28,7 @@ def __init__(self, caller, *args, **kwargs):
2828
self.button_checkRpc.setToolTip("try to connect to RPC server")
2929
self.centralBox.addWidget(self.button_checkRpc, 0, 2)
3030
self.rpcLed = QLabel()
31-
self.rpcLed.setToolTip("%s" % caller.rpcStatusMess)
31+
self.rpcLed.setToolTip(f"{caller.rpcStatusMess}")
3232
self.rpcLed.setPixmap(caller.ledGrayH_icon)
3333
self.centralBox.addWidget(self.rpcLed, 0, 3)
3434
self.lastPingBox = QWidget()
@@ -65,7 +65,7 @@ def __init__(self, caller, *args, **kwargs):
6565
self.button_checkHw.setToolTip("try to connect to Hardware Wallet")
6666
self.centralBox.addWidget(self.button_checkHw, 1, 2)
6767
self.hwLed = QLabel()
68-
self.hwLed.setToolTip("status: %s" % caller.hwStatusMess)
68+
self.hwLed.setToolTip(f"status: {caller.hwStatusMess}")
6969
self.hwLed.setPixmap(caller.ledGrayH_icon)
7070
self.centralBox.addWidget(self.hwLed, 1, 3)
7171
layout.addLayout(self.centralBox)

0 commit comments

Comments
 (0)