Skip to content

Commit

Permalink
[mypy] don't use implicit optionals
Browse files Browse the repository at this point in the history
This is explicitely prohibited by PEP 484
  • Loading branch information
PiRK committed Jan 13, 2023
1 parent 20a9aed commit e358fe1
Show file tree
Hide file tree
Showing 21 changed files with 60 additions and 48 deletions.
6 changes: 3 additions & 3 deletions electrumabc/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import hashlib
import struct
from collections import namedtuple
from typing import Tuple, Union
from typing import Optional, Tuple, Union

from . import cashaddr, networks
from .bitcoin import (
Expand Down Expand Up @@ -394,7 +394,7 @@ def from_cashaddr_string(
cls,
string: str,
*,
net: networks.AbstractNet = None,
net: Optional[networks.AbstractNet] = None,
support_arbitrary_prefix: bool = False,
):
"""Construct from a cashaddress string.
Expand Down Expand Up @@ -451,7 +451,7 @@ def from_string(
cls,
string: str,
*,
net: networks.AbstractNet = None,
net: Optional[networks.AbstractNet] = None,
support_arbitrary_prefix: bool = False,
):
"""Construct from an address string.
Expand Down
2 changes: 1 addition & 1 deletion electrumabc/base_wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def do_upgrade():
do_upgrade, _("Upgrading wallet format..."), on_finished=on_finished
)

def run_task_without_blocking_gui(self, task, *, msg: str = None) -> Any:
def run_task_without_blocking_gui(self, task, *, msg: Optional[str] = None) -> Any:
"""Perform a task in a thread without blocking the GUI.
Returns the result of 'task', or raises the same exception.
This method blocks until 'task' is finished.
Expand Down
6 changes: 3 additions & 3 deletions electrumabc/bitcoin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,13 +1508,13 @@ def __init__(self, enc, *, net=None):
)

@property
def lot(self) -> int:
def lot(self) -> Optional[int]:
"""Returns the 'lot' number if 'hasLotSequence' or None otherwise."""
if self.dec and self.hasLotSequence:
return self.entropy[4] * 4096 + self.entropy[5] * 16 + self.entropy[6] // 16

@property
def sequence(self) -> int:
def sequence(self) -> Optional[int]:
"""Returns the 'sequence' number if 'hasLotSequence' or None
otherwise."""
if self.dec and self.hasLotSequence:
Expand Down Expand Up @@ -1783,7 +1783,7 @@ def encrypt(cls, wif: str, passphrase: str, *, net=None) -> object:
def createECMult(
cls,
passphrase: str,
lot_sequence: Tuple[int, int] = None,
lot_sequence: Optional[Tuple[int, int]] = None,
compressed=True,
*,
net=None,
Expand Down
7 changes: 5 additions & 2 deletions electrumabc/contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import re
import traceback
from collections import namedtuple
from typing import List
from typing import List, Optional

import dns
from dns.exception import DNSException
Expand Down Expand Up @@ -303,7 +303,10 @@ def replace(self, old: Contact, new: Contact):
return False

def add(
self, contact: Contact, replace_old: Contact = None, unique: bool = False
self,
contact: Contact,
replace_old: Optional[Contact] = None,
unique: bool = False,
) -> bool:
"""Puts a contact in the contact list, appending it at the end.
Optionally, if replace_old is specified, will replace the entry
Expand Down
4 changes: 2 additions & 2 deletions electrumabc/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -1092,7 +1092,7 @@ def unpaired_device_infos(
self,
handler: Optional[HardwareHandlerBase],
plugin: HW_PluginBase,
devices: List[Device] = None,
devices: Optional[List[Device]] = None,
) -> List["DeviceInfo"]:
"""Returns a list of DeviceInfo objects: one for each connected,
unpaired device accepted by the plugin."""
Expand Down Expand Up @@ -1122,7 +1122,7 @@ def select_device(
plugin: HW_PluginBase,
handler: HardwareHandlerBase,
keystore: Hardware_KeyStore,
devices: List["Device"] = None,
devices: Optional[List["Device"]] = None,
) -> DeviceInfo:
"""Ask the user to select a device to use if there is more than one,
and return the DeviceInfo for the device."""
Expand Down
4 changes: 2 additions & 2 deletions electrumabc/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import hashlib
import struct
import warnings
from typing import Tuple, Union
from typing import Optional, Tuple, Union

import ecdsa

Expand Down Expand Up @@ -1574,7 +1574,7 @@ def tx_cache_get(cls, txid: str) -> object:
return None

@classmethod
def tx_cache_put(cls, tx: object, txid: str = None):
def tx_cache_put(cls, tx: object, txid: Optional[str] = None):
"""Puts a non-deserialized copy of tx into the tx_cache."""
if not tx or not tx.raw:
raise ValueError("Please pass a tx which has a valid .raw attribute!")
Expand Down
4 changes: 2 additions & 2 deletions electrumabc/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -2954,12 +2954,12 @@ def rebuild_history(self):
self.start_threads(network)
self.network.trigger_callback("wallet_updated", self)

def is_schnorr_possible(self, reason: list = None) -> bool:
def is_schnorr_possible(self, reason: Optional[list] = None) -> bool:
"""Returns True if this wallet type is compatible.
`reason` is an optional list where you would like a translated string
of why Schnorr isn't possible placed (on False return)."""
ok = bool(not self.is_multisig() and not self.is_hardware())
if not ok and isinstance(reason, list):
if not ok and reason is not None:
reason.insert(0, _("Schnorr signatures are disabled for this wallet type."))
return ok

Expand Down
22 changes: 10 additions & 12 deletions electrumabc/winconsole.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@
import ctypes
import os
import sys
from typing import Iterator, Optional

STD_OUTPUT_HANDLE = -11
FILE_TYPE_DISK = 1


def parent_process_pids() -> int:
def parent_process_pids() -> Iterator[int]:
"""
Returns all parent process PIDs, starting with the closest parent
"""
Expand All @@ -58,16 +59,15 @@ def get_console_title() -> str:
b = bytes(1024)
b_ptr = ctypes.c_char_p(b)
title = None
title_len = ctypes.windll.kernel32.GetConsoleTitleW(
b_ptr, len(b) // 2
) # GetConsoleTitleW expects size in 2-byte chars
# GetConsoleTitleW expects size in 2-byte chars
title_len = ctypes.windll.kernel32.GetConsoleTitleW(b_ptr, len(b) // 2) # type: ignore[attr-defined]
if title_len > 0:
title = b.decode("utf-16")[:title_len]
return title


def create_or_attach_console(
*, attach: bool = True, create: bool = False, title: str = None
*, attach: bool = True, create: bool = False, title: Optional[str] = None
) -> bool:
"""
Workaround to the fact that cmd.exe based execution of this program means
Expand All @@ -90,8 +90,7 @@ def create_or_attach_console(
(sys.stdout, sys.stderr) to this found and/or created console.
Always return True on success or if there was a console already,
False or None on failure (a None return indicates a missing lib or some
other unspecified exception was raised when attempting to create a console).
False on failure.
"""
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

Expand All @@ -111,7 +110,7 @@ def create_or_attach_console(
break
except ImportError:
# User's system lacks psutil
return # Return None in case caller wants to differntiate exceptional failures from regular False return
return False

created = False

Expand All @@ -134,12 +133,11 @@ def create_or_attach_console(
except OSError:
# If we get here, we likely were in MinGW / MSYS where CONOUT$ / CONIN$
# are not valid files or some other weirdness occurred. Give up.
return # return None to indicate underlying exception
return False

if title:
old_title = (
get_console_title() if not created else None
) # save the old title only if not created by us
# save the old title only if not created by us
old_title = get_console_title() if not created else None
# Set the console title, if specified
ctypes.windll.kernel32.SetConsoleTitleW(title)
if old_title is not None:
Expand Down
2 changes: 1 addition & 1 deletion electrumabc_gui/qt/avalanche/proof_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __init__(
self,
wallet: Deterministic_Wallet,
receive_address: Optional[Address] = None,
parent: QtWidgets.QWidget = None,
parent: Optional[QtWidgets.QWidget] = None,
):
CachedWalletPasswordWidget.__init__(self, wallet, parent=parent)
# This is enough width to show a whole compressed pubkey.
Expand Down
4 changes: 2 additions & 2 deletions electrumabc_gui/qt/avalanche/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(
self,
wallet: Deterministic_Wallet,
pwd: Optional[str] = None,
parent: QtWidgets.QWidget = None,
parent: Optional[QtWidgets.QWidget] = None,
):
super().__init__(parent)
self._pwd = pwd
Expand Down Expand Up @@ -168,7 +168,7 @@ def __init__(
self,
wallet: Deterministic_Wallet,
pwd: Optional[str] = None,
parent: QtWidgets.QWidget = None,
parent: Optional[QtWidgets.QWidget] = None,
additional_info: Optional[str] = None,
):
super().__init__(parent)
Expand Down
2 changes: 1 addition & 1 deletion electrumabc_gui/qt/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -3447,7 +3447,7 @@ def change_password_dialog(self):
self.status_bar.update_lock_icon(self.wallet.has_password())

def get_passphrase_dialog(
self, msg: str, title: str = None, *, permit_empty=False
self, msg: str, title: Optional[str] = None, *, permit_empty=False
) -> str:
d = PassphraseDialog(
self.wallet, self.top_level_window(), msg, title, permit_empty=permit_empty
Expand Down
5 changes: 3 additions & 2 deletions electrumabc_gui/qt/qrreader/crop_blur_effect.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Optional

from PyQt5 import QtWidgets
from PyQt5.QtCore import QObject, QPoint, QRect, Qt
Expand All @@ -36,12 +37,12 @@ class QrReaderCropBlurEffect(QtWidgets.QGraphicsBlurEffect):
BLUR_DARKEN = 0.25
BLUR_RADIUS = 8

def __init__(self, parent: QObject, crop: QRect = None):
def __init__(self, parent: QObject, crop: Optional[QRect] = None):
super().__init__(parent)
self.crop = crop
self.setBlurRadius(self.BLUR_RADIUS)

def setCrop(self, crop: QRect = None):
def setCrop(self, crop: Optional[QRect] = None):
self.crop = crop

def draw(self, painter: QPainter):
Expand Down
4 changes: 2 additions & 2 deletions electrumabc_gui/qt/qrreader/video_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from typing import List
from typing import List, Optional

from PyQt5 import QtWidgets
from PyQt5.QtCore import QPoint, QRect, QRectF, QSize, Qt
Expand All @@ -48,7 +48,7 @@ class QrReaderVideoOverlay(QtWidgets.QWidget):
QR_FINDER_OPACITY = 0.25
QR_FINDER_SIZE = 0.5

def __init__(self, parent: QtWidgets.QWidget = None):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
super().__init__(parent)

self.results = []
Expand Down
4 changes: 2 additions & 2 deletions electrumabc_gui/qt/qrreader/video_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from typing import List
from typing import List, Optional

from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import QImage
Expand All @@ -45,7 +45,7 @@ class QrReaderVideoSurface(QAbstractVideoSurface):
necessary and sends them to listeners via the frame_available event.
"""

def __init__(self, parent: QObject = None):
def __init__(self, parent: Optional[QObject] = None):
super().__init__(parent)

def present(self, frame: QVideoFrame) -> bool:
Expand Down
3 changes: 2 additions & 1 deletion electrumabc_gui/qt/qrreader/video_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Optional

from PyQt5 import QtWidgets
from PyQt5.QtGui import QPainter, QPaintEvent, QPixmap
Expand All @@ -35,7 +36,7 @@ class QrReaderVideoWidget(QtWidgets.QWidget):

USE_BILINEAR_FILTER = True

def __init__(self, parent: QtWidgets.QWidget = None):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
super().__init__(parent)

self.pixmap = None
Expand Down
4 changes: 3 additions & 1 deletion electrumabc_gui/qt/sign_verify_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@


class CollapsibleSection(QWidget):
def __init__(self, title: str, content_widget: QWidget, parent: QWidget = None):
def __init__(
self, title: str, content_widget: QWidget, parent: Optional[QWidget] = None
):
super().__init__(parent)

main_layout = QGridLayout(self)
Expand Down
3 changes: 2 additions & 1 deletion electrumabc_gui/qt/style_patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
This is used to patch the QApplication style sheet.
It reads the current stylesheet, appends our modifications and sets the new stylesheet.
"""
from typing import Optional

from PyQt5 import QtWidgets

Expand Down Expand Up @@ -37,7 +38,7 @@
"""


def patch(use_dark_theme: bool = False, darkstyle_ver: tuple = None):
def patch(use_dark_theme: bool = False, darkstyle_ver: Optional[tuple] = None):
if not use_dark_theme:
return
custom_patch = ""
Expand Down
9 changes: 5 additions & 4 deletions electrumabc_gui/qt/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from collections import namedtuple
from functools import partial, wraps
from locale import atof
from typing import Optional

from PyQt5 import QtWidgets
from PyQt5.QtCore import QObject, Qt, QThread, QTimer, pyqtSignal
Expand Down Expand Up @@ -980,7 +981,7 @@ def _updateOverlayPos(self):
x -= scrollbar_width
self.overlay_widget.move(x, y)

def addWidget(self, widget: QtWidgets.QWidget, index: int = None):
def addWidget(self, widget: QtWidgets.QWidget, index: Optional[int] = None):
if index is not None:
self.overlay_layout.insertWidget(index, widget)
else:
Expand All @@ -991,9 +992,9 @@ def addButton(
icon_name: str,
on_click,
tooltip: str,
index: int = None,
index: Optional[int] = None,
*,
text: str = None,
text: Optional[str] = None,
) -> QtWidgets.QAbstractButton:
"""icon_name may be None but then you must define text (which is
hopefully then some nice Unicode character). Both cannot be None.
Expand Down Expand Up @@ -1540,7 +1541,7 @@ class TextBrowserKeyboardFocusFilter(QtWidgets.QTextBrowser):
deactivate keyboard text selection.
"""

def __init__(self, parent: QtWidgets.QWidget = None):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
super().__init__(parent)

def focusInEvent(self, e: QFocusEvent):
Expand Down
6 changes: 4 additions & 2 deletions electrumabc_gui/qt/utils/aspect_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from typing import List
from typing import List, Optional

from PyQt5 import QtWidgets
from PyQt5.QtCore import QPoint, QRect, QSize, Qt


class FixedAspectRatioLayout(QtWidgets.QLayout):
def __init__(self, parent: QtWidgets.QWidget = None, aspect_ratio: float = 1.0):
def __init__(
self, parent: Optional[QtWidgets.QWidget] = None, aspect_ratio: float = 1.0
):
super().__init__(parent)
self.aspect_ratio = aspect_ratio
self.items: List[QtWidgets.QLayoutItem] = []
Expand Down
Loading

0 comments on commit e358fe1

Please sign in to comment.