From 6ccc3703cf018ac0822281d4f317091f8020d624 Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Wed, 11 Oct 2023 12:58:49 +0000 Subject: [PATCH] pylint throughout (excluding tests) - type comparison with isinstance() --- mmgen/addr.py | 4 ++-- mmgen/addrdata.py | 2 +- mmgen/altcoin.py | 2 +- mmgen/amt.py | 8 ++++---- mmgen/cfg.py | 2 +- mmgen/cfgfile.py | 2 +- mmgen/devtools.py | 2 +- mmgen/fileutil.py | 2 +- mmgen/flags.py | 2 +- mmgen/key.py | 4 ++-- mmgen/mn_entry.py | 2 +- mmgen/obj.py | 16 ++++++++-------- mmgen/proto/btc/regtest.py | 4 ++-- mmgen/proto/btc/tx/completed.py | 2 +- mmgen/rpc.py | 2 +- mmgen/seed.py | 2 +- mmgen/seedsplit.py | 2 +- mmgen/share/Opts.py | 2 +- mmgen/subseed.py | 2 +- mmgen/tw/shared.py | 4 ++-- mmgen/tw/view.py | 2 +- mmgen/util.py | 2 +- mmgen/xmrwallet.py | 2 +- 23 files changed, 37 insertions(+), 37 deletions(-) diff --git a/mmgen/addr.py b/mmgen/addr.py index a8d34502..1d498713 100755 --- a/mmgen/addr.py +++ b/mmgen/addr.py @@ -107,7 +107,7 @@ class AddrListID(str,Hilite,InitErrors,MMGenObject): except: mmtype = MMGenPasswordType( proto=proto, id_str=b ) else: - assert type(sid) == SeedID, f'{sid!r} not a SeedID instance' + assert isinstance(sid,SeedID), f'{sid!r} not a SeedID instance' if not isinstance(mmtype,(MMGenAddrType,MMGenPasswordType)): raise ValueError(f'{mmtype!r}: not an instance of MMGenAddrType or MMGenPasswordType') me = str.__new__(cls,sid+':'+mmtype) @@ -150,7 +150,7 @@ class CoinAddr(str,Hilite,InitErrors,MMGenObject): width = 1 trunc_ok = False def __new__(cls,proto,addr): - if type(addr) == cls: + if isinstance(addr,cls): return addr try: assert addr.isascii() and addr.isalnum(), 'not an ASCII alphanumeric string' diff --git a/mmgen/addrdata.py b/mmgen/addrdata.py index 2256446f..fd3c6b24 100755 --- a/mmgen/addrdata.py +++ b/mmgen/addrdata.py @@ -54,7 +54,7 @@ class AddrData(MMGenObject): return (list(d.values())[0][0]) if d else None def add(self,addrlist): - if type(addrlist) == AddrList: + if isinstance(addrlist,AddrList): self.al_ids[addrlist.al_id] = addrlist return True else: diff --git a/mmgen/altcoin.py b/mmgen/altcoin.py index 31266133..3664d3eb 100755 --- a/mmgen/altcoin.py +++ b/mmgen/altcoin.py @@ -516,7 +516,7 @@ class CoinInfo(object): sym,trust = e['symbol'],e['trust_level'] fix_ver_info(e,'p2pkh_info') - if type(e['p2sh_info']) == tuple: + if isinstance(e['p2sh_info'],tuple): fix_ver_info(e,'p2sh_info') for k in e.keys(): diff --git a/mmgen/amt.py b/mmgen/amt.py index e20f4ee4..aef7ca8c 100755 --- a/mmgen/amt.py +++ b/mmgen/amt.py @@ -42,7 +42,7 @@ class CoinAmt(Decimal,Hilite,InitErrors): # abstract class units = () # defined unit names, e.g. ('satoshi',...) def __new__(cls,num,from_unit=None,from_decimal=False): - if type(num) == cls: + if isinstance(num,cls): return num try: if from_unit: @@ -50,11 +50,11 @@ class CoinAmt(Decimal,Hilite,InitErrors): # abstract class assert type(num) == int,'value is not an integer' me = Decimal.__new__(cls,num * getattr(cls,from_unit)) elif from_decimal: - assert type(num) == Decimal, f'number must be of type Decimal, not {type(num).__name__})' + assert isinstance(num,Decimal), f'number must be of type Decimal, not {type(num).__name__})' me = Decimal.__new__(cls,num.quantize(Decimal('10') ** -cls.max_prec)) else: - for t in cls.forbidden_types: - assert type(num) is not t, f'number is of forbidden type {t.__name__}' + for bad_type in cls.forbidden_types: + assert not isinstance(num,bad_type), f'number is of forbidden type {bad_type.__name__}' me = Decimal.__new__(cls,str(num)) assert me.normalize().as_tuple()[-1] >= -cls.max_prec,'too many decimal places in coin amount' if cls.max_amt: diff --git a/mmgen/cfg.py b/mmgen/cfg.py index f37e888c..a2237d63 100755 --- a/mmgen/cfg.py +++ b/mmgen/cfg.py @@ -719,7 +719,7 @@ def check_opts(cfg): # Raises exception if any check fails def opt_is_in_list(val,tlist,desc_pfx=''): if val not in tlist: - q,sep = (('',','),("'","','"))[type(tlist[0]) == str] + q,sep = (('',','),("'","','"))[isinstance(tlist[0],str)] die( 'UserOptError', '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format( v = val, w = get_desc(desc_pfx), diff --git a/mmgen/cfgfile.py b/mmgen/cfgfile.py index 4a0056d2..219d5555 100755 --- a/mmgen/cfgfile.py +++ b/mmgen/cfgfile.py @@ -68,7 +68,7 @@ class cfg_file: m = re.fullmatch(r'((\s+\w+:\S+)+)',' '+value) # expect one or more colon-separated values if m: return dict([i.split(':') for i in m[1].split()]) - elif isinstance(refval,list) or isinstance(refval,tuple): + elif isinstance(refval,(list,tuple)): m = re.fullmatch(r'((\s+\S+)+)',' '+value) # expect single value or list if m: ret = m[1].split() diff --git a/mmgen/devtools.py b/mmgen/devtools.py index 32a861ea..46b736c5 100755 --- a/mmgen/devtools.py +++ b/mmgen/devtools.py @@ -176,7 +176,7 @@ class MMGenObjectMethods: # mixin class for MMGenObject if isList(e) or isDict(e): out.append('{:>{l}}{:<10} {:16}'.format( '', k, f'<{type(e).__name__}>', l=(lvl*8)+4 )) do_list(out,e,lvl=lvl,is_dict=isDict(e)) - elif hasattr(e,'pfmt') and callable(e.pfmt) and type(e) != type: + elif hasattr(e,'pfmt') and callable(e.pfmt) and not isinstance(e,type): out.append('{:>{l}}{:10} {}'.format( '', k, diff --git a/mmgen/fileutil.py b/mmgen/fileutil.py index 9ff8cc70..1e1cd443 100755 --- a/mmgen/fileutil.py +++ b/mmgen/fileutil.py @@ -143,7 +143,7 @@ def _open_or_die(filename,mode,silent=False): except: die(2,'' if silent else 'Unable to open file {!r} for {}'.format( - ({0:'STDIN',1:'STDOUT',2:'STDERR'}[filename] if type(filename) == int else filename), + ({0:'STDIN',1:'STDOUT',2:'STDERR'}[filename] if isinstance(filename,int) else filename), ('reading' if 'r' in mode else 'writing') )) diff --git a/mmgen/flags.py b/mmgen/flags.py index fd68dcd0..425d86ab 100755 --- a/mmgen/flags.py +++ b/mmgen/flags.py @@ -65,7 +65,7 @@ class ClassFlags(AttrCtrl): self.not_available_error(name) if self._name == 'flags': - assert type(val) is bool, f'{val!r} not boolean' + assert isinstance(val,bool), f'{val!r} not boolean' old_val = getattr(self,name) if val and old_val: die( 'ClassFlagsError', f'{self._desc} {name!r} already set' ) diff --git a/mmgen/key.py b/mmgen/key.py index 0287f642..3333837e 100755 --- a/mmgen/key.py +++ b/mmgen/key.py @@ -31,7 +31,7 @@ class WifKey(str,Hilite,InitErrors): width = 53 color = 'blue' def __new__(cls,proto,wif): - if type(wif) == cls: + if isinstance(wif,cls): return wif try: assert wif.isascii() and wif.isalnum(), 'not an ASCII alphanumeric string' @@ -70,7 +70,7 @@ class PrivKey(bytes,Hilite,InitErrors,MMGenObject): # initialize with (priv_bin,compressed), WIF or self def __new__(cls,proto,s=None,compressed=None,wif=None,pubkey_type=None): - if type(s) == cls: + if isinstance(s,cls): return s if wif: try: diff --git a/mmgen/mn_entry.py b/mmgen/mn_entry.py index 9cb507d0..258fae5e 100755 --- a/mmgen/mn_entry.py +++ b/mmgen/mn_entry.py @@ -204,7 +204,7 @@ class MnEntryModeMinimal(MnEntryMode): elif ch in ascii_lowercase: s += ch ret = mne.idx(s,'minimal',lo_idx=lo,hi_idx=hi) - if type(ret) != tuple: + if not isinstance(ret,tuple): return ret lo,hi = ret else: diff --git a/mmgen/obj.py b/mmgen/obj.py index 3f009329..3faa0d88 100755 --- a/mmgen/obj.py +++ b/mmgen/obj.py @@ -110,7 +110,7 @@ class ImmutableAttr: # Descriptor if include_proto: assert typeconv, 'ImmutableAttr_check2' if set_none_ok: - assert typeconv and type(dtype) != str, 'ImmutableAttr_check3' + assert typeconv and not isinstance(dtype,str), 'ImmutableAttr_check3' if dtype is None: # use instance-defined conversion function for this attribute @@ -229,7 +229,7 @@ class MMGenRange(tuple,InitErrors,MMGenObject): try: if len(args) == 1: s = args[0] - if type(s) == cls: + if isinstance(s,cls): return s assert isinstance(s,str),'not a string or string subclass' ss = s.split('-',1) @@ -270,7 +270,7 @@ class Int(int,Hilite,InitErrors): color = 'red' def __new__(cls,n,base=10): - if type(n) == cls: + if isinstance(n,cls): return n try: me = int.__new__(cls,str(n),base) @@ -312,7 +312,7 @@ class HexStr(str,Hilite,InitErrors): hexcase = 'lower' trunc_ok = False def __new__(cls,s,case=None): - if type(s) == cls: + if isinstance(s,cls): return s if case == None: case = cls.hexcase @@ -351,13 +351,13 @@ class MMGenLabel(str,Hilite,InitErrors): min_len = 0 max_screen_width = 0 # if != 0, overrides max_len desc = 'label' - def __new__(cls,s,msg=None): - if type(s) == cls: + def __new__(cls,s): + if isinstance(s,cls): return s for k in ( cls.forbidden, cls.allowed ): - assert type(k) == list + assert isinstance(k,list) for ch in k: - assert type(ch) == str and len(ch) == 1 + assert isinstance(ch,str) and len(ch) == 1 try: s = s.strip() for ch in s: diff --git a/mmgen/proto/btc/regtest.py b/mmgen/proto/btc/regtest.py index e9c5cb08..0fc314a8 100755 --- a/mmgen/proto/btc/regtest.py +++ b/mmgen/proto/btc/regtest.py @@ -216,11 +216,11 @@ class MMGenRegtest(MMGenObject): async def cli(self,*args): ret = await self.rpc_call(*cliargs_convert(args)) - print(ret if type(ret) == str else json.dumps(ret,cls=json_encoder,indent=4)) + print(ret if isinstance(ret,str) else json.dumps(ret,cls=json_encoder,indent=4)) async def wallet_cli(self,wallet,*args): ret = await self.rpc_call(*cliargs_convert(args),wallet=wallet) - print(ret if type(ret) == str else json.dumps(ret,cls=json_encoder,indent=4)) + print(ret if isinstance(ret,str) else json.dumps(ret,cls=json_encoder,indent=4)) async def cmd(self,args): ret = getattr(self,args[0])(*args[1:]) diff --git a/mmgen/proto/btc/tx/completed.py b/mmgen/proto/btc/tx/completed.py index 2f43fe6b..e5f18b30 100755 --- a/mmgen/proto/btc/tx/completed.py +++ b/mmgen/proto/btc/tx/completed.py @@ -33,7 +33,7 @@ class Completed(Base,TxBase.Completed): if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH ti['scriptSig'][:6] == '16' + self.proto.witness_vernum_hex + '14' ): assert 'witness' in ti, 'missing witness' - assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness' + assert isinstance(ti['witness'],list) and len(ti['witness']) == 2, 'malformed witness' assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length' assert mmti.mmtype == ('S','B')[ti['scriptSig']==''], fs.format('witness-type',mmti.mmtype) else: # non-witness diff --git a/mmgen/rpc.py b/mmgen/rpc.py index 9d92a935..aab4c704 100755 --- a/mmgen/rpc.py +++ b/mmgen/rpc.py @@ -54,7 +54,7 @@ class IPPort(str,Hilite,InitErrors): min_len = 9 # 0.0.0.0:0 max_len = 21 # 255.255.255.255:65535 def __new__(cls,s): - if type(s) == cls: + if isinstance(s,cls): return s try: m = re.fullmatch(r'{q}\.{q}\.{q}\.{q}:(\d{{1,10}})'.format(q=r'([0-9]{1,3})'),s) diff --git a/mmgen/seed.py b/mmgen/seed.py index a71c0d2f..7b44e47c 100755 --- a/mmgen/seed.py +++ b/mmgen/seed.py @@ -29,7 +29,7 @@ class SeedID(str,Hilite,InitErrors): width = 8 trunc_ok = False def __new__(cls,seed=None,sid=None): - if type(sid) == cls: + if isinstance(sid,cls): return sid try: if seed: diff --git a/mmgen/seedsplit.py b/mmgen/seedsplit.py index b3eef381..89b26a0d 100755 --- a/mmgen/seedsplit.py +++ b/mmgen/seedsplit.py @@ -40,7 +40,7 @@ class MasterShareIdx(MMGenIdx): class SeedSplitSpecifier(str,Hilite,InitErrors,MMGenObject): color = 'red' def __new__(cls,s): - if type(s) == cls: + if isinstance(s,cls): return s try: arr = s.split(':') diff --git a/mmgen/share/Opts.py b/mmgen/share/Opts.py index 3ecd0a5f..3bc040a0 100755 --- a/mmgen/share/Opts.py +++ b/mmgen/share/Opts.py @@ -26,7 +26,7 @@ from collections import namedtuple pat = re.compile(r'^-([a-zA-Z0-9-]), --([a-zA-Z0-9-]{2,64})(=| )(.+)') def make_usage_str(prog_name,caller,data): - lines = [data.strip()] if type(data) == str else data + lines = [data.strip()] if isinstance(data,str) else data indent,col1_w = { 'help': (2,len(prog_name)+1), 'user': (0,len('USAGE:')), diff --git a/mmgen/subseed.py b/mmgen/subseed.py index 6279053e..c7c801ba 100755 --- a/mmgen/subseed.py +++ b/mmgen/subseed.py @@ -34,7 +34,7 @@ class SubSeedIdx(str,Hilite,InitErrors): color = 'red' trunc_ok = False def __new__(cls,s): - if type(s) == cls: + if isinstance(s,cls): return s try: assert isinstance(s,str),'not a string or string subclass' diff --git a/mmgen/tw/shared.py b/mmgen/tw/shared.py index e8a76685..7c3e7c11 100755 --- a/mmgen/tw/shared.py +++ b/mmgen/tw/shared.py @@ -21,7 +21,7 @@ class TwMMGenID(str,Hilite,InitErrors,MMGenObject): width = 0 trunc_ok = False def __new__(cls,proto,id_str): - if type(id_str) == cls: + if isinstance(id_str,cls): return id_str try: ret = addr = disp = MMGenID(proto,id_str) @@ -54,7 +54,7 @@ class TwLabel(str,InitErrors,MMGenObject): exc = 'BadTwLabel' passthru_excs = ('BadTwComment',) def __new__(cls,proto,text): - if type(text) == cls: + if isinstance(text,cls): return text try: ts = text.split(None,1) diff --git a/mmgen/tw/view.py b/mmgen/tw/view.py index 4355b050..523695f9 100755 --- a/mmgen/tw/view.py +++ b/mmgen/tw/view.py @@ -250,7 +250,7 @@ class TwView(MMGenObject,metaclass=AsyncInit): if key not in self.sort_funcs: die(1,f'{key!r}: invalid sort key. Valid options: {" ".join(self.sort_funcs)}') self.sort_key = key - assert type(reverse) == bool + assert isinstance(reverse,bool) save = self.data.copy() self.data.sort(key=self.sort_funcs[key],reverse=reverse or self.reverse) if self.data != save: diff --git a/mmgen/util.py b/mmgen/util.py index 392156d9..e73665a8 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -222,7 +222,7 @@ def list_gen(*data): assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)' def gen(): for d in data: - assert type(d) == list, f'{type(d).__name__} != list' + assert isinstance(d,list), f'{type(d).__name__} != list' if len(d) == 1: yield d[0] elif d[-1]: diff --git a/mmgen/xmrwallet.py b/mmgen/xmrwallet.py index 593439b4..0cd991b6 100755 --- a/mmgen/xmrwallet.py +++ b/mmgen/xmrwallet.py @@ -83,7 +83,7 @@ class XMRWalletAddrSpec(str,Hilite,InitErrors,MMGenObject): min_len = 5 # 1:0:0 max_len = 14 # 9999:9999:9999 def __new__(cls,arg1,arg2=None,arg3=None): - if type(arg1) == cls: + if isinstance(arg1,cls): return arg1 try: