pylint throughout (excluding tests) - type comparison with isinstance()

This commit is contained in:
The MMGen Project 2023-10-11 12:58:49 +00:00
commit 6ccc3703cf
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
23 changed files with 37 additions and 37 deletions

View file

@ -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'

View file

@ -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:

View file

@ -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():

View file

@ -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:

View file

@ -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),

View file

@ -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()

View file

@ -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,

View file

@ -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')
))

View file

@ -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' )

View file

@ -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:

View file

@ -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:

View file

@ -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:

View file

@ -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:])

View file

@ -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

View file

@ -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)

View file

@ -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:

View file

@ -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(':')

View file

@ -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:')),

View file

@ -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'

View file

@ -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)

View file

@ -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:

View file

@ -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]:

View file

@ -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: