Skip to content

Commit 83e1479

Browse files
committed
plugin: clean up imports, style
1 parent 3d6198e commit 83e1479

File tree

1 file changed

+26
-29
lines changed

1 file changed

+26
-29
lines changed

electrum/plugin.py

+26-29
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python
22
#
33
# Electrum - lightweight Bitcoin client
4-
# Copyright (C) 2015 Thomas Voegtlin
4+
# Copyright (C) 2015-2024 Thomas Voegtlin
55
#
66
# Permission is hereby granted, free of charge, to any person
77
# obtaining a copy of this software and associated documentation files
@@ -22,23 +22,22 @@
2222
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2323
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2424
# SOFTWARE.
25+
2526
import os
2627
import pkgutil
2728
import importlib.util
2829
import time
2930
import threading
3031
import traceback
3132
import sys
32-
import json
33+
import aiohttp
34+
3335
from typing import (NamedTuple, Any, Union, TYPE_CHECKING, Optional, Tuple,
34-
Dict, Iterable, List, Sequence, Callable, TypeVar, Mapping, Set)
36+
Dict, Iterable, List, Sequence, Callable, TypeVar, Mapping)
3537
import concurrent
3638
import zipimport
3739
from concurrent import futures
3840
from functools import wraps, partial
39-
from enum import IntEnum
40-
from packaging.version import parse as parse_version
41-
from electrum.version import ELECTRUM_VERSION
4241

4342
from .i18n import _
4443
from .util import (profiler, DaemonThread, UserCancelled, ThreadJob, UserFacingException)
@@ -59,7 +58,6 @@
5958
hooks = {}
6059

6160

62-
6361
class Plugins(DaemonThread):
6462

6563
LOGGING_SHORTCUT = 'p'
@@ -89,7 +87,7 @@ def __init__(self, config: SimpleConfig, gui_name):
8987
def descriptions(self):
9088
return dict(list(self.internal_plugin_metadata.items()) + list(self.external_plugin_metadata.items()))
9189

92-
def find_internal_plugins(self) -> Mapping[str, dict]:
90+
def find_internal_plugins(self):
9391
"""Populates self.internal_plugin_metadata
9492
"""
9593
iter_modules = list(pkgutil.iter_modules([self.pkgpath]))
@@ -165,10 +163,9 @@ def check_plugin_hash(self, name: str)-> bool:
165163
return True
166164

167165
async def download_external_plugin(self, name):
168-
import aiohttp
169166
metadata = self.external_plugin_metadata.get(name)
170167
if metadata is None:
171-
raise Exception("unknown external plugin %s" % name)
168+
raise Exception(f"unknown external plugin {name}")
172169
url = metadata['download_url']
173170
filename = self.external_plugin_path(name)
174171
async with aiohttp.ClientSession() as session:
@@ -179,7 +176,7 @@ async def download_external_plugin(self, name):
179176
fd.write(chunk)
180177
if not self.check_plugin_hash(name):
181178
os.unlink(filename)
182-
raise Exception("wrong plugin hash %s" % name)
179+
raise Exception(f"wrong plugin hash {name}")
183180

184181
def load_external_plugin(self, name):
185182
if name in self.plugins:
@@ -188,31 +185,30 @@ def load_external_plugin(self, name):
188185
# on startup, or added by manual user installation after that point.
189186
metadata = self.external_plugin_metadata.get(name)
190187
if metadata is None:
191-
self.logger.exception("attempted to load unknown external plugin %s" % name)
188+
self.logger.exception(f"attempted to load unknown external plugin {name}")
192189
return
193190
filename = self.external_plugin_path(name)
194191
if not os.path.exists(filename):
195192
return
196193
if not self.check_plugin_hash(name):
197-
self.logger.exception("wrong hash for plugin '%s'" % name)
194+
self.logger.exception(f"wrong hash for plugin '{name}'")
198195
os.unlink(filename)
199196
return
200197
try:
201198
zipfile = zipimport.zipimporter(filename)
202199
except zipimport.ZipImportError:
203-
self.logger.exception("unable to load zip plugin '%s'" % filename)
200+
self.logger.exception(f"unable to load zip plugin '{filename}'")
204201
return
205202
try:
206203
module = zipfile.load_module(name)
207204
except zipimport.ZipImportError as e:
208205
self.logger.exception(f"unable to load zip plugin '{filename}' package '{name}'")
209206
return
210-
sys.modules['electrum_external_plugins.'+ name] = module
207+
sys.modules['electrum_external_plugins.' + name] = module
211208
full_name = f'electrum_external_plugins.{name}.{self.gui_name}'
212209
spec = importlib.util.find_spec(full_name)
213210
if spec is None:
214-
raise RuntimeError("%s implementation for %s plugin not found"
215-
% (self.gui_name, name))
211+
raise RuntimeError(f"{self.gui_name} implementation for {name} plugin not found")
216212
module = importlib.util.module_from_spec(spec)
217213
self._register_module(spec, module)
218214
if sys.version_info >= (3, 10):
@@ -248,7 +244,7 @@ def load_external_plugins(self):
248244
try:
249245
self.load_external_plugin(name)
250246
except BaseException as e:
251-
traceback.print_exc(file=sys.stdout) # shouldn't this be... suppressed unless -v?
247+
traceback.print_exc(file=sys.stdout) # shouldn't this be... suppressed unless -v?
252248
self.logger.exception(f"cannot initialize plugin {name} {e!r}")
253249

254250
def get(self, name):
@@ -271,11 +267,10 @@ def load_plugin(self, name) -> 'BasePlugin':
271267
def load_internal_plugin(self, name) -> 'BasePlugin':
272268
if name in self.plugins:
273269
return self.plugins[name]
274-
full_name = f'electrum.plugins.{name}' + f'.{self.gui_name}'
270+
full_name = f'electrum.plugins.{name}.{self.gui_name}'
275271
spec = importlib.util.find_spec(full_name)
276272
if spec is None:
277-
raise RuntimeError("%s implementation for %s plugin not found"
278-
% (self.gui_name, name))
273+
raise RuntimeError(f"{self.gui_name} implementation for {name} plugin not found")
279274
try:
280275
module = importlib.util.module_from_spec(spec)
281276
spec.loader.exec_module(module)
@@ -350,6 +345,7 @@ def get_hardware_support(self):
350345
def register_wallet_type(self, name, gui_good, wallet_type):
351346
from .wallet import register_wallet_type, register_constructor
352347
self.logger.info(f"registering wallet type {(wallet_type, name)}")
348+
353349
def loader():
354350
plugin = self.get_plugin(name)
355351
register_constructor(wallet_type, plugin.wallet_class)
@@ -358,6 +354,7 @@ def loader():
358354

359355
def register_keystore(self, name, gui_good, details):
360356
from .keystore import register_keystore
357+
361358
def dynamic_constructor(d):
362359
return self.get_plugin(name).keystore_class(d)
363360
if details[0] == 'hardware':
@@ -406,7 +403,7 @@ def __init__(self, parent, config: 'SimpleConfig', name):
406403
self.parent = parent # type: Plugins # The plugins object
407404
self.name = name
408405
self.config = config
409-
self.wallet = None # fixme: this field should not exist
406+
self.wallet = None # fixme: this field should not exist
410407
Logger.__init__(self)
411408
# add self to hooks
412409
for k in dir(self):
@@ -443,7 +440,7 @@ def thread_jobs(self):
443440
return []
444441

445442
def is_enabled(self):
446-
return self.is_available() and self.config.get('enable_plugin_'+self.name) is True
443+
return self.is_available() and self.config.get('enable_plugin_' + self.name) is True
447444

448445
def is_available(self):
449446
return True
@@ -466,6 +463,7 @@ def read_file(self, filename: str) -> bytes:
466463
s = myfile.read()
467464
return s
468465

466+
469467
class DeviceUnpairableError(UserFacingException): pass
470468
class HardwarePluginLibraryUnavailable(Exception): pass
471469
class CannotAutoSelectDevice(Exception): pass
@@ -551,7 +549,7 @@ def assert_runs_in_hwd_thread():
551549

552550

553551
class DeviceMgr(ThreadJob):
554-
'''Manages hardware clients. A client communicates over a hardware
552+
"""Manages hardware clients. A client communicates over a hardware
555553
channel with the device.
556554
557555
In addition to tracking device HID IDs, the device manager tracks
@@ -579,7 +577,7 @@ class DeviceMgr(ThreadJob):
579577
the HID IDs.
580578
581579
This plugin is thread-safe. Currently only devices supported by
582-
hidapi are implemented.'''
580+
hidapi are implemented."""
583581

584582
def __init__(self, config: SimpleConfig):
585583
ThreadJob.__init__(self)
@@ -691,7 +689,7 @@ def client_for_keystore(self, plugin: 'HW_PluginBase', handler: Optional['Hardwa
691689
allow_user_interaction: bool = True) -> Optional['HardwareClientBase']:
692690
self.logger.info("getting client for keystore")
693691
if handler is None:
694-
raise Exception(_("Handler not found for") + ' ' + plugin.name + '\n' + _("A library is probably missing."))
692+
raise Exception(_("Handler not found for {}").format(plugin.name) + '\n' + _("A library is probably missing."))
695693
handler.update_status(False)
696694
pcode = keystore.pairing_code()
697695
client = None
@@ -756,7 +754,7 @@ def force_pair_keystore(
756754
try:
757755
client_xpub = client.get_xpub(derivation, xtype)
758756
except (UserCancelled, RuntimeError):
759-
# Bad / cancelled PIN / passphrase
757+
# Bad / cancelled PIN / passphrase
760758
client_xpub = None
761759
if client_xpub == xpub:
762760
keystore.opportunistically_fill_in_missing_info_from_device(client)
@@ -928,8 +926,7 @@ def scan_devices(self) -> Sequence['Device']:
928926
try:
929927
new_devices = f()
930928
except BaseException as e:
931-
self.logger.error('custom device enum failed. func {}, error {}'
932-
.format(str(f), repr(e)))
929+
self.logger.error(f'custom device enum failed. func {str(f)}, error {e!r}')
933930
else:
934931
devices.extend(new_devices)
935932

0 commit comments

Comments
 (0)