Browse Source

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

The MMGen Project 1 year ago
parent
commit
6ccc3703cf

+ 2 - 2
mmgen/addr.py

@@ -107,7 +107,7 @@ class AddrListID(str,Hilite,InitErrors,MMGenObject):
 				except:
 				except:
 					mmtype = MMGenPasswordType( proto=proto, id_str=b )
 					mmtype = MMGenPasswordType( proto=proto, id_str=b )
 			else:
 			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)):
 				if not isinstance(mmtype,(MMGenAddrType,MMGenPasswordType)):
 					raise ValueError(f'{mmtype!r}: not an instance of MMGenAddrType or MMGenPasswordType')
 					raise ValueError(f'{mmtype!r}: not an instance of MMGenAddrType or MMGenPasswordType')
 			me = str.__new__(cls,sid+':'+mmtype)
 			me = str.__new__(cls,sid+':'+mmtype)
@@ -150,7 +150,7 @@ class CoinAddr(str,Hilite,InitErrors,MMGenObject):
 	width = 1
 	width = 1
 	trunc_ok = False
 	trunc_ok = False
 	def __new__(cls,proto,addr):
 	def __new__(cls,proto,addr):
-		if type(addr) == cls:
+		if isinstance(addr,cls):
 			return addr
 			return addr
 		try:
 		try:
 			assert addr.isascii() and addr.isalnum(), 'not an ASCII alphanumeric string'
 			assert addr.isascii() and addr.isalnum(), 'not an ASCII alphanumeric string'

+ 1 - 1
mmgen/addrdata.py

@@ -54,7 +54,7 @@ class AddrData(MMGenObject):
 		return (list(d.values())[0][0]) if d else None
 		return (list(d.values())[0][0]) if d else None
 
 
 	def add(self,addrlist):
 	def add(self,addrlist):
-		if type(addrlist) == AddrList:
+		if isinstance(addrlist,AddrList):
 			self.al_ids[addrlist.al_id] = addrlist
 			self.al_ids[addrlist.al_id] = addrlist
 			return True
 			return True
 		else:
 		else:

+ 1 - 1
mmgen/altcoin.py

@@ -516,7 +516,7 @@ class CoinInfo(object):
 			sym,trust = e['symbol'],e['trust_level']
 			sym,trust = e['symbol'],e['trust_level']
 
 
 			fix_ver_info(e,'p2pkh_info')
 			fix_ver_info(e,'p2pkh_info')
-			if type(e['p2sh_info']) == tuple:
+			if isinstance(e['p2sh_info'],tuple):
 				fix_ver_info(e,'p2sh_info')
 				fix_ver_info(e,'p2sh_info')
 
 
 			for k in e.keys():
 			for k in e.keys():

+ 4 - 4
mmgen/amt.py

@@ -42,7 +42,7 @@ class CoinAmt(Decimal,Hilite,InitErrors): # abstract class
 	units    = ()     # defined unit names, e.g. ('satoshi',...)
 	units    = ()     # defined unit names, e.g. ('satoshi',...)
 
 
 	def __new__(cls,num,from_unit=None,from_decimal=False):
 	def __new__(cls,num,from_unit=None,from_decimal=False):
-		if type(num) == cls:
+		if isinstance(num,cls):
 			return num
 			return num
 		try:
 		try:
 			if from_unit:
 			if from_unit:
@@ -50,11 +50,11 @@ class CoinAmt(Decimal,Hilite,InitErrors): # abstract class
 				assert type(num) == int,'value is not an integer'
 				assert type(num) == int,'value is not an integer'
 				me = Decimal.__new__(cls,num * getattr(cls,from_unit))
 				me = Decimal.__new__(cls,num * getattr(cls,from_unit))
 			elif from_decimal:
 			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))
 				me = Decimal.__new__(cls,num.quantize(Decimal('10') ** -cls.max_prec))
 			else:
 			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))
 				me = Decimal.__new__(cls,str(num))
 			assert me.normalize().as_tuple()[-1] >= -cls.max_prec,'too many decimal places in coin amount'
 			assert me.normalize().as_tuple()[-1] >= -cls.max_prec,'too many decimal places in coin amount'
 			if cls.max_amt:
 			if cls.max_amt:

+ 1 - 1
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=''):
 	def opt_is_in_list(val,tlist,desc_pfx=''):
 		if val not in tlist:
 		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(
 			die( 'UserOptError', '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'.format(
 				v = val,
 				v = val,
 				w = get_desc(desc_pfx),
 				w = get_desc(desc_pfx),

+ 1 - 1
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
 			m = re.fullmatch(r'((\s+\w+:\S+)+)',' '+value) # expect one or more colon-separated values
 			if m:
 			if m:
 				return dict([i.split(':') for i in m[1].split()])
 				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
 			m = re.fullmatch(r'((\s+\S+)+)',' '+value)     # expect single value or list
 			if m:
 			if m:
 				ret = m[1].split()
 				ret = m[1].split()

+ 1 - 1
mmgen/devtools.py

@@ -176,7 +176,7 @@ class MMGenObjectMethods: # mixin class for MMGenObject
 			if isList(e) or isDict(e):
 			if isList(e) or isDict(e):
 				out.append('{:>{l}}{:<10} {:16}'.format( '', k, f'<{type(e).__name__}>', l=(lvl*8)+4 ))
 				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))
 				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(
 				out.append('{:>{l}}{:10} {}'.format(
 					'',
 					'',
 					k,
 					k,

+ 1 - 1
mmgen/fileutil.py

@@ -143,7 +143,7 @@ def _open_or_die(filename,mode,silent=False):
 	except:
 	except:
 		die(2,'' if silent else
 		die(2,'' if silent else
 			'Unable to open file {!r} for {}'.format(
 			'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')
 				('reading' if 'r' in mode else 'writing')
 			))
 			))
 
 

+ 1 - 1
mmgen/flags.py

@@ -65,7 +65,7 @@ class ClassFlags(AttrCtrl):
 				self.not_available_error(name)
 				self.not_available_error(name)
 
 
 			if self._name == 'flags':
 			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)
 				old_val = getattr(self,name)
 				if val and old_val:
 				if val and old_val:
 					die( 'ClassFlagsError', f'{self._desc} {name!r} already set' )
 					die( 'ClassFlagsError', f'{self._desc} {name!r} already set' )

+ 2 - 2
mmgen/key.py

@@ -31,7 +31,7 @@ class WifKey(str,Hilite,InitErrors):
 	width = 53
 	width = 53
 	color = 'blue'
 	color = 'blue'
 	def __new__(cls,proto,wif):
 	def __new__(cls,proto,wif):
-		if type(wif) == cls:
+		if isinstance(wif,cls):
 			return wif
 			return wif
 		try:
 		try:
 			assert wif.isascii() and wif.isalnum(), 'not an ASCII alphanumeric string'
 			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
 	# initialize with (priv_bin,compressed), WIF or self
 	def __new__(cls,proto,s=None,compressed=None,wif=None,pubkey_type=None):
 	def __new__(cls,proto,s=None,compressed=None,wif=None,pubkey_type=None):
-		if type(s) == cls:
+		if isinstance(s,cls):
 			return s
 			return s
 		if wif:
 		if wif:
 			try:
 			try:

+ 1 - 1
mmgen/mn_entry.py

@@ -204,7 +204,7 @@ class MnEntryModeMinimal(MnEntryMode):
 			elif ch in ascii_lowercase:
 			elif ch in ascii_lowercase:
 				s += ch
 				s += ch
 				ret = mne.idx(s,'minimal',lo_idx=lo,hi_idx=hi)
 				ret = mne.idx(s,'minimal',lo_idx=lo,hi_idx=hi)
-				if type(ret) != tuple:
+				if not isinstance(ret,tuple):
 					return ret
 					return ret
 				lo,hi = ret
 				lo,hi = ret
 			else:
 			else:

+ 8 - 8
mmgen/obj.py

@@ -110,7 +110,7 @@ class ImmutableAttr: # Descriptor
 		if include_proto:
 		if include_proto:
 			assert typeconv, 'ImmutableAttr_check2'
 			assert typeconv, 'ImmutableAttr_check2'
 		if set_none_ok:
 		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:
 		if dtype is None:
 			# use instance-defined conversion function for this attribute
 			# use instance-defined conversion function for this attribute
@@ -229,7 +229,7 @@ class MMGenRange(tuple,InitErrors,MMGenObject):
 		try:
 		try:
 			if len(args) == 1:
 			if len(args) == 1:
 				s = args[0]
 				s = args[0]
-				if type(s) == cls:
+				if isinstance(s,cls):
 					return s
 					return s
 				assert isinstance(s,str),'not a string or string subclass'
 				assert isinstance(s,str),'not a string or string subclass'
 				ss = s.split('-',1)
 				ss = s.split('-',1)
@@ -270,7 +270,7 @@ class Int(int,Hilite,InitErrors):
 	color = 'red'
 	color = 'red'
 
 
 	def __new__(cls,n,base=10):
 	def __new__(cls,n,base=10):
-		if type(n) == cls:
+		if isinstance(n,cls):
 			return n
 			return n
 		try:
 		try:
 			me = int.__new__(cls,str(n),base)
 			me = int.__new__(cls,str(n),base)
@@ -312,7 +312,7 @@ class HexStr(str,Hilite,InitErrors):
 	hexcase = 'lower'
 	hexcase = 'lower'
 	trunc_ok = False
 	trunc_ok = False
 	def __new__(cls,s,case=None):
 	def __new__(cls,s,case=None):
-		if type(s) == cls:
+		if isinstance(s,cls):
 			return s
 			return s
 		if case == None:
 		if case == None:
 			case = cls.hexcase
 			case = cls.hexcase
@@ -351,13 +351,13 @@ class MMGenLabel(str,Hilite,InitErrors):
 	min_len = 0
 	min_len = 0
 	max_screen_width = 0 # if != 0, overrides max_len
 	max_screen_width = 0 # if != 0, overrides max_len
 	desc = 'label'
 	desc = 'label'
-	def __new__(cls,s,msg=None):
-		if type(s) == cls:
+	def __new__(cls,s):
+		if isinstance(s,cls):
 			return s
 			return s
 		for k in ( cls.forbidden, cls.allowed ):
 		for k in ( cls.forbidden, cls.allowed ):
-			assert type(k) == list
+			assert isinstance(k,list)
 			for ch in k:
 			for ch in k:
-				assert type(ch) == str and len(ch) == 1
+				assert isinstance(ch,str) and len(ch) == 1
 		try:
 		try:
 			s = s.strip()
 			s = s.strip()
 			for ch in s:
 			for ch in s:

+ 2 - 2
mmgen/proto/btc/regtest.py

@@ -216,11 +216,11 @@ class MMGenRegtest(MMGenObject):
 
 
 	async def cli(self,*args):
 	async def cli(self,*args):
 		ret = await self.rpc_call(*cliargs_convert(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):
 	async def wallet_cli(self,wallet,*args):
 		ret = await self.rpc_call(*cliargs_convert(args),wallet=wallet)
 		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):
 	async def cmd(self,args):
 		ret = getattr(self,args[0])(*args[1:])
 		ret = getattr(self,args[0])(*args[1:])

+ 1 - 1
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
 			if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH
 					ti['scriptSig'][:6] == '16' + self.proto.witness_vernum_hex + '14' ):
 					ti['scriptSig'][:6] == '16' + self.proto.witness_vernum_hex + '14' ):
 				assert 'witness' in ti, 'missing witness'
 				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 len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
 				assert mmti.mmtype == ('S','B')[ti['scriptSig']==''], fs.format('witness-type',mmti.mmtype)
 				assert mmti.mmtype == ('S','B')[ti['scriptSig']==''], fs.format('witness-type',mmti.mmtype)
 			else: # non-witness
 			else: # non-witness

+ 1 - 1
mmgen/rpc.py

@@ -54,7 +54,7 @@ class IPPort(str,Hilite,InitErrors):
 	min_len = 9  # 0.0.0.0:0
 	min_len = 9  # 0.0.0.0:0
 	max_len = 21 # 255.255.255.255:65535
 	max_len = 21 # 255.255.255.255:65535
 	def __new__(cls,s):
 	def __new__(cls,s):
-		if type(s) == cls:
+		if isinstance(s,cls):
 			return s
 			return s
 		try:
 		try:
 			m = re.fullmatch(r'{q}\.{q}\.{q}\.{q}:(\d{{1,10}})'.format(q=r'([0-9]{1,3})'),s)
 			m = re.fullmatch(r'{q}\.{q}\.{q}\.{q}:(\d{{1,10}})'.format(q=r'([0-9]{1,3})'),s)

+ 1 - 1
mmgen/seed.py

@@ -29,7 +29,7 @@ class SeedID(str,Hilite,InitErrors):
 	width = 8
 	width = 8
 	trunc_ok = False
 	trunc_ok = False
 	def __new__(cls,seed=None,sid=None):
 	def __new__(cls,seed=None,sid=None):
-		if type(sid) == cls:
+		if isinstance(sid,cls):
 			return sid
 			return sid
 		try:
 		try:
 			if seed:
 			if seed:

+ 1 - 1
mmgen/seedsplit.py

@@ -40,7 +40,7 @@ class MasterShareIdx(MMGenIdx):
 class SeedSplitSpecifier(str,Hilite,InitErrors,MMGenObject):
 class SeedSplitSpecifier(str,Hilite,InitErrors,MMGenObject):
 	color = 'red'
 	color = 'red'
 	def __new__(cls,s):
 	def __new__(cls,s):
-		if type(s) == cls:
+		if isinstance(s,cls):
 			return s
 			return s
 		try:
 		try:
 			arr = s.split(':')
 			arr = s.split(':')

+ 1 - 1
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})(=| )(.+)')
 pat = re.compile(r'^-([a-zA-Z0-9-]), --([a-zA-Z0-9-]{2,64})(=| )(.+)')
 
 
 def make_usage_str(prog_name,caller,data):
 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 = {
 	indent,col1_w = {
 		'help': (2,len(prog_name)+1),
 		'help': (2,len(prog_name)+1),
 		'user': (0,len('USAGE:')),
 		'user': (0,len('USAGE:')),

+ 1 - 1
mmgen/subseed.py

@@ -34,7 +34,7 @@ class SubSeedIdx(str,Hilite,InitErrors):
 	color = 'red'
 	color = 'red'
 	trunc_ok = False
 	trunc_ok = False
 	def __new__(cls,s):
 	def __new__(cls,s):
-		if type(s) == cls:
+		if isinstance(s,cls):
 			return s
 			return s
 		try:
 		try:
 			assert isinstance(s,str),'not a string or string subclass'
 			assert isinstance(s,str),'not a string or string subclass'

+ 2 - 2
mmgen/tw/shared.py

@@ -21,7 +21,7 @@ class TwMMGenID(str,Hilite,InitErrors,MMGenObject):
 	width = 0
 	width = 0
 	trunc_ok = False
 	trunc_ok = False
 	def __new__(cls,proto,id_str):
 	def __new__(cls,proto,id_str):
-		if type(id_str) == cls:
+		if isinstance(id_str,cls):
 			return id_str
 			return id_str
 		try:
 		try:
 			ret = addr = disp = MMGenID(proto,id_str)
 			ret = addr = disp = MMGenID(proto,id_str)
@@ -54,7 +54,7 @@ class TwLabel(str,InitErrors,MMGenObject):
 	exc = 'BadTwLabel'
 	exc = 'BadTwLabel'
 	passthru_excs = ('BadTwComment',)
 	passthru_excs = ('BadTwComment',)
 	def __new__(cls,proto,text):
 	def __new__(cls,proto,text):
-		if type(text) == cls:
+		if isinstance(text,cls):
 			return text
 			return text
 		try:
 		try:
 			ts = text.split(None,1)
 			ts = text.split(None,1)

+ 1 - 1
mmgen/tw/view.py

@@ -250,7 +250,7 @@ class TwView(MMGenObject,metaclass=AsyncInit):
 		if key not in self.sort_funcs:
 		if key not in self.sort_funcs:
 			die(1,f'{key!r}: invalid sort key.  Valid options: {" ".join(self.sort_funcs)}')
 			die(1,f'{key!r}: invalid sort key.  Valid options: {" ".join(self.sort_funcs)}')
 		self.sort_key = key
 		self.sort_key = key
-		assert type(reverse) == bool
+		assert isinstance(reverse,bool)
 		save = self.data.copy()
 		save = self.data.copy()
 		self.data.sort(key=self.sort_funcs[key],reverse=reverse or self.reverse)
 		self.data.sort(key=self.sort_funcs[key],reverse=reverse or self.reverse)
 		if self.data != save:
 		if self.data != save:

+ 1 - 1
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)'
 	assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)'
 	def gen():
 	def gen():
 		for d in data:
 		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:
 			if len(d) == 1:
 				yield d[0]
 				yield d[0]
 			elif d[-1]:
 			elif d[-1]:

+ 1 - 1
mmgen/xmrwallet.py

@@ -83,7 +83,7 @@ class XMRWalletAddrSpec(str,Hilite,InitErrors,MMGenObject):
 	min_len = 5  # 1:0:0
 	min_len = 5  # 1:0:0
 	max_len = 14 # 9999:9999:9999
 	max_len = 14 # 9999:9999:9999
 	def __new__(cls,arg1,arg2=None,arg3=None):
 	def __new__(cls,arg1,arg2=None,arg3=None):
-		if type(arg1) == cls:
+		if isinstance(arg1,cls):
 			return arg1
 			return arg1
 
 
 		try:
 		try: