pylint throughout (excluding tests) - use "is" for bool,None,type equality

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

View file

@ -110,7 +110,7 @@ class AddrFile(MMGenObject):
fs = ' {:<%s} {:<34}{}' % len(str(p.data[-1].idx))
for e in p.data:
c = ' ' + e.comment if add_comments and e.comment else ''
if type(p) == KeyList:
if type(p) is KeyList:
out.append(fs.format( e.idx, f'{p.al_id.mmtype.wif_label}: {e.sec.wif}', c ))
elif type(p).__name__ == 'PasswordList':
out.append(fs.format(e.idx,e.passwd,c))
@ -119,7 +119,7 @@ class AddrFile(MMGenObject):
if p.has_keys:
if self.cfg.b16:
out.append(fs.format( '', f'orig_hex: {e.sec.orig_bytes.hex()}', c ))
if type(self) != ViewKeyAddrFile:
if type(self) is not ViewKeyAddrFile:
out.append(fs.format( '', f'{p.al_id.mmtype.wif_label}: {e.sec.wif}', c ))
for k in ('viewkey','wallet_passwd'):
v = getattr(e,k)
@ -154,7 +154,7 @@ class AddrFile(MMGenObject):
a = le(**{ 'proto': p.proto, 'idx':int(idx), p.main_attr:addr, 'comment':comment })
if p.has_keys: # order: wif,(orig_hex),viewkey,wallet_passwd
if type(self) != ViewKeyAddrFile:
if type(self) is not ViewKeyAddrFile:
d = self.get_line(lines)
assert d[0] == p.al_id.mmtype.wif_label+':', iifs.format(d[0],p.al_id.mmtype.wif_label)
a.sec = PrivKey(proto=p.proto,wif=d[1])
@ -168,7 +168,7 @@ class AddrFile(MMGenObject):
ret.append(a)
if type(self) != ViewKeyAddrFile and p.has_keys and p.ka_validity_chk != False:
if type(self) is not ViewKeyAddrFile and p.has_keys and p.ka_validity_chk is not False:
def verify_keys():
from .addrgen import KeyGenerator,AddrGenerator
@ -230,7 +230,7 @@ class AddrFile(MMGenObject):
proto = init_proto( p.cfg, coin=coin, network=network )
if mmtype_key == None:
if mmtype_key is None:
mmtype_key = proto.mmtypes[0]
return ( proto, proto.addr_type(mmtype_key) )

View file

@ -66,9 +66,9 @@ def AddrGenerator(cfg,proto,addr_type):
from .addr import MMGenAddrType
if type(addr_type) == str:
if type(addr_type) is str:
addr_type = MMGenAddrType(proto=proto,id_str=addr_type)
elif type(addr_type) == MMGenAddrType:
elif type(addr_type) is MMGenAddrType:
assert addr_type in proto.mmtypes, f'{addr_type}: invalid address type for coin {proto.coin}'
else:
raise TypeError(f'{type(addr_type)}: incorrect argument type for {cls.__name__}()')

View file

@ -216,16 +216,16 @@ class AddrList(MMGenObject): # Address info for a single seed ID
self.fmt_data = ''
self.chksum = None
if self.al_id == None:
if self.al_id is None:
return
if type(self) == ViewKeyAddrList:
if type(self) is ViewKeyAddrList:
if not 'viewkey' in self.al_id.mmtype.extra_attrs:
die(1,f'viewkeys not supported for address type {self.al_id.mmtype.desc!r}')
self.id_str = AddrListIDStr(self)
if type(self) == KeyList:
if type(self) is KeyList:
return
if do_chksum and not skip_chksum:
@ -288,7 +288,7 @@ class AddrList(MMGenObject): # Address info for a single seed ID
e.viewkey = ag.to_viewkey(data)
if gen_wallet_passwd:
e.wallet_passwd = self.gen_wallet_passwd(
e.viewkey.encode() if type(self) == ViewKeyAddrList else e.sec )
e.viewkey.encode() if type(self) is ViewKeyAddrList else e.sec )
elif self.gen_passwds:
e.passwd = self.gen_passwd(e.sec) # TODO - own type

View file

@ -42,7 +42,7 @@ from .cfg import gc,Config
from .util import msg
def test_equal(desc,a,b,*cdata):
if type(a) == int:
if type(a) is int:
a = hex(a)
b = hex(b)
(network,coin,e,b_desc,verbose) = cdata
@ -625,7 +625,7 @@ class CoinInfo(object):
except:
pass
else:
if bl == True or coin in bl:
if bl is True or coin in bl:
if verbose:
msg(f'Tool {tool!r} blacklisted for coin {coin}, addr_type {addr_type!r}')
return None
@ -708,7 +708,7 @@ def init_genonly_altcoins(usr_coin=None,testnet=False):
networks = ['mainnet'] + (['testnet'] if testnet else [])
network = 'testnet' if testnet else 'mainnet'
if usr_coin == None:
if usr_coin is None:
for network in networks:
data[network] = CoinInfo.get_supported_coins(network)
trust_level = 0

View file

@ -47,7 +47,7 @@ class CoinAmt(Decimal,Hilite,InitErrors): # abstract class
try:
if from_unit:
assert from_unit in cls.units, f'{from_unit!r}: unrecognized denomination for {cls.__name__}'
assert type(num) == int,'value is not an integer'
assert type(num) is int,'value is not an integer'
me = Decimal.__new__(cls,num * getattr(cls,from_unit))
elif from_decimal:
assert isinstance(num,Decimal), f'number must be of type Decimal, not {type(num).__name__})'

View file

@ -121,9 +121,9 @@ class baseconv(object):
If 'seed', output length will be mapped from input length using data in seedlen_map.
If an integer, the string, hex string or byte output will be padded to this length.
"""
if pad == None:
if pad is None:
return 0
elif type(pad) == int:
elif type(pad) is int:
return pad
elif pad == 'seed':
return seed_pad_func()
@ -132,7 +132,7 @@ class baseconv(object):
def tohex(self,words_arg,pad=None):
"convert string or list data of instance base to a hexadecimal string"
return self.tobytes(words_arg,pad//2 if type(pad)==int else pad).hex()
return self.tobytes(words_arg, pad//2 if type(pad) is int else pad).hex()
def tobytes(self,words_arg,pad=None):
"convert string or list data of instance base to byte string"

View file

@ -110,7 +110,7 @@ class bip39(baseconv):
def fromhex(self,seed_hex,pad=None,tostr=False):
assert is_hex_str(seed_hex),'seed data not a hexadecimal string'
assert tostr == False,"'tostr' must be False for 'bip39'"
assert tostr is False,"'tostr' must be False for 'bip39'"
assert pad in (None,'seed'), f"{pad}: invalid 'pad' argument (must be None or 'seed')"
wl = self.digits

View file

@ -675,7 +675,7 @@ class Config(Lockable):
def _die_on_incompatible_opts(self):
for group in self._incompatible_opts:
bad = [k for k in self.__dict__ if k in group and getattr(self,k) != None]
bad = [k for k in self.__dict__ if k in group and getattr(self,k) is not None]
if len(bad) > 1:
die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
@ -881,7 +881,7 @@ def conv_type(
d = f' in {src!r}' if src else '',
e = type(refval).__name__ ))
if type(refval) == bool:
if type(refval) is bool:
v = str(val).lower()
ret = (
True if v in ('true','yes','1','on') else

View file

@ -148,7 +148,7 @@ class cfg_file_sample(cfg_file):
if line == '':
in_chunk = False
elif line.startswith('#'):
if in_chunk == False:
if in_chunk is False:
if chunk:
yield process_chunk(chunk,last_nonblank)
chunk = [line]

View file

@ -306,7 +306,7 @@ class Crypto:
desc,
urand = {'data':b'', 'counter':0} ):
assert type(rand_bytes) == bytes, 'add_user_random_chk1'
assert type(rand_bytes) is bytes, 'add_user_random_chk1'
if self.cfg.usr_randchars:

View file

@ -170,7 +170,7 @@ def write_data_to_file(
if cfg.quiet:
ask_overwrite = False
if ask_write_default_yes == False or ask_write_prompt:
if ask_write_default_yes is False or ask_write_prompt:
ask_write = True
def do_stdout():

View file

@ -74,7 +74,7 @@ class PrivKey(bytes,Hilite,InitErrors,MMGenObject):
return s
if wif:
try:
assert s == None,"'wif' and key hex args are mutually exclusive"
assert s is None,"'wif' and key hex args are mutually exclusive"
assert wif.isascii() and wif.isalnum(), 'not an ASCII alphanumeric string'
k = proto.decode_wif(wif) # raises exception on error
me = bytes.__new__(cls,k.sec)
@ -100,7 +100,7 @@ class PrivKey(bytes,Hilite,InitErrors,MMGenObject):
me = bytes.__new__(cls,s)
else:
assert compressed is not None, "'compressed' arg missing"
assert type(compressed) == bool,(
assert type(compressed) is bool,(
f"'compressed' must be of type bool, not {type(compressed).__name__}" )
me = bytes.__new__( cls, proto.preprocess_key(s,pubkey_type) )
me.wif = WifKey( proto, proto.encode_wif(me,pubkey_type,compressed) )

View file

@ -126,7 +126,7 @@ class ImmutableAttr: # Descriptor
else:
"check this attribute's type"
def assign_with_check(instance,value):
if type(value) == dtype:
if type(value) is dtype:
return value
raise TypeError('Attribute {!r} of {} instance must of type {}'.format(
self.name,
@ -171,7 +171,7 @@ class ListItemAttr(ImmutableAttr):
return None
def setattr_condition(self,instance):
return getattr(instance,self.name) == None or self.reassign_ok
return getattr(instance,self.name) is None or self.reassign_ok
def __delete__(self,instance):
if self.delete_ok:
@ -205,7 +205,7 @@ class MMGenListItem(MMGenObject):
raise ValueError(f'Non-keyword args not allowed in {type(self).__name__!r} constructor')
for k,v in kwargs.items():
if v != None:
if v is not None:
setattr(self,k,v)
# Require all immutables to be initialized. Check performed only when testing.
@ -274,11 +274,11 @@ class Int(int,Hilite,InitErrors):
return n
try:
me = int.__new__(cls,str(n),base)
if cls.min_val != None:
if cls.min_val is not None:
assert me >= cls.min_val, f'is less than cls.min_val ({cls.min_val})'
if cls.max_val != None:
if cls.max_val is not None:
assert me <= cls.max_val, f'is greater than cls.max_val ({cls.max_val})'
if cls.max_digits != None:
if cls.max_digits is not None:
assert len(str(me)) <= cls.max_digits, f'has more than {cls.max_digits} digits'
return me
except Exception as e:
@ -314,7 +314,7 @@ class HexStr(str,Hilite,InitErrors):
def __new__(cls,s,case=None):
if isinstance(s,cls):
return s
if case == None:
if case is None:
case = cls.hexcase
from .util import hexdigits_lc,hexdigits_uc
try:

View file

@ -229,7 +229,7 @@ class MMGenRegtest(MMGenObject):
async def fork(self,coin): # currently disabled
proto = init_proto( self.cfg, coin, False )
if not [f for f in proto.forks if f[2] == proto.coin.lower() and f[3] == True]:
if not [f for f in proto.forks if f[2] == proto.coin.lower() and f[3] is True]:
die(1,f'Coin {proto.coin} is not a replayable fork of coin {coin}')
gmsg(f'Creating fork from coin {coin} to coin {proto.coin}')

View file

@ -170,7 +170,7 @@ class BitcoinRPCClient(RPCClient,metaclass=AsyncInit):
if block0 != self.proto.block0:
raise ValueError(f'Invalid Genesis block for {self.proto.cls_name} protocol')
for fork in self.proto.forks:
if fork.height == None or self.blockcount < fork.height:
if fork.height is None or self.blockcount < fork.height:
break
if fork.hash != await self.call('getblockhash',fork.height):
die(3,f'Bad block hash at fork block {fork.height}. Is this the {fork.name} chain?')
@ -286,7 +286,7 @@ class BitcoinRPCClient(RPCClient,metaclass=AsyncInit):
d = self.cached['blockchaininfo']
try:
if d['softforks']['segwit']['active'] == True:
if d['softforks']['segwit']['active'] is True:
return True
except:
pass

View file

@ -52,7 +52,7 @@ class BitcoinTwCtl(TwCtl):
async def rescan_blockchain(self,start,stop):
start = start or 0
endless = stop == None
endless = stop is None
CR = '\n' if self.cfg.test_suite else '\r'
if not ( start >= 0 and (stop if stop is not None else start) >= start ):

View file

@ -141,7 +141,7 @@ class BitcoinTwTransaction:
return self.parent.date_formatter[age_fmt](self.rpc,self.time)
def txid_disp(self,color,width=None):
return self.txid.hl(color=color) if width == None else self.txid.truncate(width=width,color=color)
return self.txid.hl(color=color) if width is None else self.txid.truncate(width=width,color=color)
def vouts_list_disp(self,src,color,indent=''):

View file

@ -32,7 +32,7 @@ class Bump(Completed,New,TxBase.Bump):
def convert_and_check_fee(self,fee,desc):
ret = super().convert_and_check_fee(fee,desc)
if ret == False:
if ret is False:
return ret
if ret < self.min_fee:
msg('{} {c}: {} fee too small. Minimum fee: {} {c} ({} {})'.format(

View file

@ -124,7 +124,7 @@ class TxInfo(TxInfo):
# format (the number of seconds elapsed since 1970-01-01T00:00 UTC). The transaction can be
# added to any block whose block time is greater than the locktime.
num = locktime or self.tx.locktime
if num == None:
if num is None:
return '(None)'
elif num >= 5 * 10**6:
import time

View file

@ -69,10 +69,10 @@ class New(Base,TxBase.New):
def convert_and_check_fee(self,fee,desc):
abs_fee = self.feespec2abs(fee,self.estimate_size())
if abs_fee == None:
if abs_fee is None:
raise ValueError(f'{fee}: cannot convert {self.rel_fee_desc} to {self.coin}'
+ ' because transaction size is unknown')
if abs_fee == False:
if abs_fee is False:
err = f'{fee!r}: invalid TX fee (not a {self.coin} amount or {self.rel_fee_desc} specification)'
elif abs_fee > self.proto.max_tx_fee:
err = f'{abs_fee} {self.coin}: {desc} fee too large (maximum fee: {self.proto.max_tx_fee} {self.coin})'

Some files were not shown because too many files have changed in this diff Show more