diff options
author | Charles Harris <charlesr.harris@gmail.com> | 2013-04-26 21:31:12 -0600 |
---|---|---|
committer | Charles Harris <charlesr.harris@gmail.com> | 2013-05-02 21:13:17 -0600 |
commit | dec4f4b76ae9b2b953bcc093275aa59f93adf6fd (patch) | |
tree | 13a9a50d087f6c55a6afb942437afc99110cd6f5 | |
parent | 63a9f197d040b5479b772fd3925274fc984ffd24 (diff) | |
download | numpy-dec4f4b76ae9b2b953bcc093275aa59f93adf6fd.tar.gz |
MAINT: Apply 2to3 idioms fixer.
The idioms fixer makes the following replacements.
1) int <- bool
2) comparison or identity of types <- isinstance
3) a.sort() <- sorted(a)
There were two problems that needed to be dealt with after the
application of the fixer. First, the replacement of comparison or
identity of types by isinstance was not always correct. The isinstance
function returns true for subtypes whereas many of the places where the
fixer made a substitution needed to check for exact type equality.
Second, the sorted function was applied to arrays, but because it treats
them as iterators and constructs a sorted list from the result, that is
the wrong thing to do.
Closes #3062.
39 files changed, 109 insertions, 118 deletions
diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 549431306..ad711f888 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -836,8 +836,7 @@ def make_arrays(funcdict): # code1list = [] code2list = [] - names = list(funcdict.keys()) - names.sort() + names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] funclist = [] @@ -902,8 +901,7 @@ def make_arrays(funcdict): def make_ufuncs(funcdict): code3list = [] - names = list(funcdict.keys()) - names.sort() + names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] mlist = [] diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index ba89637eb..c34348e22 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -1552,7 +1552,7 @@ def sum(a, axis=None, dtype=None, out=None, keepdims=False): out[...] = res return out return res - elif not (type(a) is mu.ndarray): + elif type(a) is not mu.ndarray: try: sum = a.sum except AttributeError: @@ -1953,7 +1953,7 @@ def amax(a, axis=None, out=None, keepdims=False): 4.0 """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: amax = a.max except AttributeError: @@ -2024,7 +2024,7 @@ def amin(a, axis=None, out=None, keepdims=False): 0.0 """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: amin = a.min except AttributeError: @@ -2154,7 +2154,7 @@ def prod(a, axis=None, dtype=None, out=None, keepdims=False): True """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: prod = a.prod except AttributeError: @@ -2527,7 +2527,7 @@ def mean(a, axis=None, dtype=None, out=None, keepdims=False): 0.55000000074505806 """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: mean = a.mean return mean(axis=axis, dtype=dtype, out=out) @@ -2629,7 +2629,7 @@ def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): 0.44999999925552653 """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: std = a.std return std(axis=axis, dtype=dtype, out=out, ddof=ddof) @@ -2732,7 +2732,7 @@ def var(a, axis=None, dtype=None, out=None, ddof=0, 0.20250000000000001 """ - if not (type(a) is mu.ndarray): + if type(a) is not mu.ndarray: try: var = a.var return var(axis=axis, dtype=dtype, out=out, ddof=ddof) diff --git a/numpy/core/records.py b/numpy/core/records.py index 4fe1f8444..d0f82a25c 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -173,7 +173,7 @@ class format_parser: if (names): if (type(names) in [list, tuple]): pass - elif (type(names) == str): + elif isinstance(names, str): names = names.split(',') else: raise NameError("illegal input names %s" % repr(names)) diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index 8ab48f2d1..376097f7b 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -88,7 +88,7 @@ def test_array_astype(): b = a.astype('f4', subok=False, copy=False) assert_equal(a, b) assert_(not (a is b)) - assert_(type(b) != np.matrix) + assert_(type(b) is not np.matrix) # Make sure converting from string object to fixed length string # does not truncate. diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 9947a4660..3a6118f06 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -1270,14 +1270,14 @@ class TestIsclose(object): def test_masked_arrays(self): x = np.ma.masked_where([True, True, False], np.arange(3)) - assert_(type(x) == type(isclose(2, x))) + assert_(type(x) is type(isclose(2, x))) x = np.ma.masked_where([True, True, False], [nan, inf, nan]) - assert_(type(x) == type(isclose(inf, x))) + assert_(type(x) is type(isclose(inf, x))) x = np.ma.masked_where([True, True, False], [nan, nan, nan]) y = isclose(nan, x, equal_nan=True) - assert_(type(x) == type(y)) + assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) @@ -1409,7 +1409,7 @@ class TestLikeFuncs(TestCase): assert_(type(b) is np.matrix) b = like_function(a, subok=False) - assert_(not (type(b) is np.matrix)) + assert_(type(b) is not np.matrix) def test_ones_like(self): self.check_like_function(np.ones_like, 1) diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index 4e00b1cbc..0dc9cd1a5 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -355,7 +355,7 @@ if ctypes is not None: shape = [] ob = array_type - while type(ob) == _ARRAY_TYPE: + while type(ob) is _ARRAY_TYPE: shape.append(ob._length_) ob = ob._type_ shape = tuple(shape) diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index af59d687e..51a349aea 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -403,7 +403,7 @@ def simple_version_match(pat=r'[-.\d]+', ignore='', start=''): if not m: return None pos = m.end() - while 1: + while True: m = re.search(pat, version_string[pos:]) if not m: return None diff --git a/numpy/distutils/conv_template.py b/numpy/distutils/conv_template.py index 173853b6c..cb03fc7c3 100644 --- a/numpy/distutils/conv_template.py +++ b/numpy/distutils/conv_template.py @@ -120,7 +120,7 @@ def parse_structure(astr, level): ind = 0 line = 0 spanlist = [] - while 1: + while True: start = astr.find(loopbeg, ind) if start == -1: break diff --git a/numpy/distutils/cpuinfo.py b/numpy/distutils/cpuinfo.py index 775929fa1..64ad055d3 100644 --- a/numpy/distutils/cpuinfo.py +++ b/numpy/distutils/cpuinfo.py @@ -82,7 +82,7 @@ class CPUInfoBase(object): if not name.startswith('_'): if hasattr(self,'_'+name): attr = getattr(self,'_'+name) - if type(attr) is types.MethodType: + if isinstance(attr, types.MethodType): return lambda func=self._try_call,attr=attr : func(attr) else: return lambda : None @@ -499,7 +499,7 @@ class Win32CPUInfo(CPUInfoBase): "\s+stepping\s+(?P<STP>\d+)",re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 - while 1: + while True: try: proc=winreg.EnumKey(chnd,pnum) except winreg.error: diff --git a/numpy/distutils/fcompiler/ibm.py b/numpy/distutils/fcompiler/ibm.py index 5811be876..e5061bd18 100644 --- a/numpy/distutils/fcompiler/ibm.py +++ b/numpy/distutils/fcompiler/ibm.py @@ -45,8 +45,7 @@ class IBMFCompiler(FCompiler): # If the output of xlf does not contain version info # (that's the case with xlf 8.1, for instance) then # let's try another method: - l = os.listdir(xlf_dir) - l.sort() + l = sorted(os.listdir(xlf_dir)) l.reverse() l = [d for d in l if os.path.isfile(os.path.join(xlf_dir,d,'xlf.cfg'))] if l: diff --git a/numpy/distutils/from_template.py b/numpy/distutils/from_template.py index 5d6bea3ca..9052cf74e 100644 --- a/numpy/distutils/from_template.py +++ b/numpy/distutils/from_template.py @@ -65,13 +65,13 @@ def parse_structure(astr): spanlist = [] ind = 0 - while 1: + while True: m = routine_start_re.search(astr,ind) if m is None: break start = m.start() if function_start_re.match(astr,start,m.end()): - while 1: + while True: i = astr.rfind('\n',ind,start) if i==-1: break diff --git a/numpy/doc/__init__.py b/numpy/doc/__init__.py index 86d45f618..b6f1fa71c 100644 --- a/numpy/doc/__init__.py +++ b/numpy/doc/__init__.py @@ -4,9 +4,8 @@ import os ref_dir = os.path.join(os.path.dirname(__file__)) -__all__ = [f[:-3] for f in os.listdir(ref_dir) if f.endswith('.py') and - not f.startswith('__')] -__all__.sort() +__all__ = sorted(f[:-3] for f in os.listdir(ref_dir) if f.endswith('.py') and + not f.startswith('__')) for f in __all__: __import__(__name__ + '.' + f) diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index e391430f5..e835090f7 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -491,9 +491,9 @@ def getmultilineblock(rout,blockname,comment=1,counter=0): except KeyError: return if not r: return - if counter>0 and type(r) is type(''): + if counter > 0 and isinstance(r, str): return - if type(r) is type([]): + if isinstance(r, list): if counter>=len(r): return r = r[counter] if r[:3]=="'''": @@ -598,7 +598,7 @@ def gentitle(name): return '/*%s %s %s*/'%(l*'*',name,l*'*') def flatlist(l): - if type(l)==list: + if isinstance(l, list): return reduce(lambda x,y,f=flatlist:x+f(y),l,[]) return [l] @@ -607,9 +607,9 @@ def stripcomma(s): return s def replace(str,d,defaultsep=''): - if type(d)==list: + if isinstance(d, list): return [replace(str, _m, defaultsep) for _m in d] - if type(str)==list: + if isinstance(str, list): return [replace(_m, d, defaultsep) for _m in str] for k in 2*list(d.keys()): if k=='separatorsfor': @@ -618,14 +618,14 @@ def replace(str,d,defaultsep=''): sep=d['separatorsfor'][k] else: sep=defaultsep - if type(d[k])==list: + if isinstance(d[k], list): str=str.replace('#%s#'%(k),sep.join(flatlist(d[k]))) else: str=str.replace('#%s#'%(k),d[k]) return str def dictappend(rd,ar): - if type(ar)==list: + if isinstance(ar, list): for a in ar: rd=dictappend(rd,a) return rd @@ -633,15 +633,15 @@ def dictappend(rd,ar): if k[0]=='_': continue if k in rd: - if type(rd[k])==str: + if isinstance(rd[k], str): rd[k]=[rd[k]] - if type(rd[k])==list: - if type(ar[k])==list: + if isinstance(rd[k], list): + if isinstance(ar[k], list): rd[k]=rd[k]+ar[k] else: rd[k].append(ar[k]) - elif type(rd[k])==dict: - if type(ar[k])==dict: + elif isinstance(rd[k], dict): + if isinstance(ar[k], dict): if k=='separatorsfor': for k1 in ar[k].keys(): if k1 not in rd[k]: @@ -654,7 +654,7 @@ def dictappend(rd,ar): def applyrules(rules,d,var={}): ret={} - if type(rules)==list: + if isinstance(rules, list): for r in rules: rr=applyrules(r,d,var) ret=dictappend(ret,rr) @@ -671,9 +671,9 @@ def applyrules(rules,d,var={}): for k in rules.keys(): if k=='separatorsfor': ret[k]=rules[k]; continue - if type(rules[k])==str: + if isinstance(rules[k], str): ret[k]=replace(rules[k],d) - elif type(rules[k])==list: + elif isinstance(rules[k], list): ret[k]=[] for i in rules[k]: ar=applyrules({k:i},d,var) @@ -681,13 +681,13 @@ def applyrules(rules,d,var={}): ret[k].append(ar[k]) elif k[0]=='_': continue - elif type(rules[k])==dict: + elif isinstance(rules[k], dict): ret[k]=[] for k1 in rules[k].keys(): - if type(k1)==types.FunctionType and k1(var): - if type(rules[k][k1])==list: + if isinstance(k1, types.FunctionType) and k1(var): + if isinstance(rules[k][k1], list): for i in rules[k][k1]: - if type(i)==dict: + if isinstance(i, dict): res=applyrules({'supertext':i},d,var) if 'supertext' in res: i=res['supertext'] @@ -695,7 +695,7 @@ def applyrules(rules,d,var={}): ret[k].append(replace(i,d)) else: i=rules[k][k1] - if type(i)==dict: + if isinstance(i, dict): res=applyrules({'supertext':i},d) if 'supertext' in res: i=res['supertext'] @@ -703,7 +703,7 @@ def applyrules(rules,d,var={}): ret[k].append(replace(i,d)) else: errmess('applyrules: ignoring rule %s.\n'%repr(rules[k])) - if type(ret[k])==list: + if isinstance(ret[k], list): if len(ret[k])==1: ret[k]=ret[k][0] if ret[k]==[]: diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py index 85e679060..f80ab06f0 100644 --- a/numpy/f2py/cb_rules.py +++ b/numpy/f2py/cb_rules.py @@ -466,7 +466,7 @@ def buildcallback(rout,um): if '_break' in r: break if 'args' in rd and 'optargs' in rd: - if type(rd['optargs'])==type([]): + if isinstance(rd['optargs'], list): rd['optargs']=rd['optargs']+[""" #ifndef F2PY_CB_RETURNCOMPLEX , @@ -482,7 +482,7 @@ def buildcallback(rout,um): , #endif """] - if type(rd['docreturn'])==list: + if isinstance(rd['docreturn'], list): rd['docreturn']=stripcomma(replace('#docreturn#',{'docreturn':rd['docreturn']})) optargs=stripcomma(replace('#docsignopt#', {'docsignopt':rd['docsignopt']} @@ -499,10 +499,10 @@ def buildcallback(rout,um): rd['docstrsigns']=[] rd['latexdocstrsigns']=[] for k in ['docstrreq','docstropt','docstrout','docstrcbs']: - if k in rd and type(rd[k])==list: + if k in rd and isinstance(rd[k], list): rd['docstrsigns']=rd['docstrsigns']+rd[k] k='latex'+k - if k in rd and type(rd[k])==list: + if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns']=rd['latexdocstrsigns']+rd[k][0:1]+\ ['\\begin{description}']+rd[k][1:]+\ ['\\end{description}'] @@ -515,7 +515,7 @@ def buildcallback(rout,um): ar=applyrules(cb_routine_rules,rd) cfuncs.callbacks[rd['name']]=ar['body'] - if type(ar['need'])==str: + if isinstance(ar['need'], str): ar['need']=[ar['need']] if 'need' in rd: diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index a16a07d59..2229c3e24 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -1128,10 +1128,10 @@ def buildcfuncs(): def append_needs(need,flag=1): global outneeds,needs - if type(need)==list: + if isinstance(need, list): for n in need: append_needs(n,flag) - elif type(need)==str: + elif isinstance(need, str): if not need: return if need in includes0: n = 'includes0' @@ -1160,7 +1160,7 @@ def append_needs(need,flag=1): if need in needs: for nn in needs[need]: t=append_needs(nn,0) - if type(t)==dict: + if isinstance(t, dict): for nnn in t.keys(): if nnn in tmp: tmp[nnn]=tmp[nnn]+t[nnn] @@ -1176,7 +1176,7 @@ def append_needs(need,flag=1): if need in needs: for nn in needs[need]: t=append_needs(nn,flag) - if type(t)==dict: + if isinstance(t, dict): for nnn in t.keys(): if nnn in tmp: tmp[nnn]=t[nnn]+tmp[nnn] diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py index bfeaf4c9b..dd44e3326 100644 --- a/numpy/f2py/common_rules.py +++ b/numpy/f2py/common_rules.py @@ -121,7 +121,7 @@ def buildhooks(m): dadd('\\item[]{{}\\verb@%s@{}}'%(capi_maps.getarrdocsign(n,vars[n]))) if hasnote(vars[n]): note = vars[n]['note'] - if type(note) is type([]): note='\n'.join(note) + if isinstance(note, list): note='\n'.join(note) dadd('--- %s'%(note)) dadd('\\end{description}') ret['docs'].append('"\t/%s/ %s\\n"'%(name,','.join(map(lambda v,d:v+d,inames,idims)))) diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index c86a15407..2ee8eb9a1 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -297,7 +297,7 @@ def readfortrancode(ffile,dowithline=show,istop=1): spacedigits=[' '] + [str(_m) for _m in range(10)] filepositiontext='' fin=fileinput.FileInput(ffile) - while 1: + while True: l=fin.readline() if not l: break if fin.isfirstline(): @@ -381,7 +381,7 @@ def readfortrancode(ffile,dowithline=show,istop=1): elif sourcecodeform=='free': if not cont and ext=='.pyf' and mline_mark.match(l): l = l + '\n' - while 1: + while True: lc = fin.readline() if not lc: errmess('Unexpected end of file when reading multiline\n') @@ -1167,7 +1167,7 @@ def analyzeline(m,case,line): groupcache[groupcounter]['f2pyenhancements'] = {} d = groupcache[groupcounter]['f2pyenhancements'] if m.group('this')=='usercode' and 'usercode' in d: - if type(d['usercode']) is type(''): + if isinstance(d['usercode'], str): d['usercode'] = [d['usercode']] d['usercode'].append(m.group('after')) else: @@ -1522,7 +1522,7 @@ def postcrack2(block,tab='',param_map=None): global f90modulevars if not f90modulevars: return block - if type(block)==list: + if isinstance(block, list): ret = [] for g in block: g = postcrack2(g,tab=tab+'\t',param_map=param_map) @@ -1559,7 +1559,7 @@ def postcrack(block,args=None,tab=''): determine expression types if in argument list """ global usermodules,onlyfunctions - if type(block)==list: + if isinstance(block, list): gret=[] uret=[] for g in block: @@ -1571,7 +1571,7 @@ def postcrack(block,args=None,tab=''): gret.append(g) return uret+gret setmesstext(block) - if (not type(block)==dict) and 'block' not in block: + if not isinstance(block, dict) and 'block' not in block: raise Exception('postcrack: Expected block dictionary instead of ' + \ str(block)) if 'name' in block and not block['name']=='unknown_interface': @@ -1819,12 +1819,12 @@ def getarrlen(dl,args,star='*'): except: edl.append(dl[0]) try: edl.append(myeval(dl[1],{},{})) except: edl.append(dl[1]) - if type(edl[0]) is type(0): + if isinstance(edl[0], int): p1 = 1-edl[0] if p1==0: d = str(dl[1]) elif p1<0: d = '%s-%s'%(dl[1],-p1) else: d = '%s+%s'%(dl[1],p1) - elif type(edl[1]) is type(0): + elif isinstance(edl[1], int): p1 = 1+edl[1] if p1==0: d='-(%s)' % (dl[0]) else: d='%s-(%s)' % (p1,dl[0]) @@ -2042,7 +2042,7 @@ def get_parameters(vars, global_params={}): params[n] = v #print params outmess('get_parameters: got "%s" on %s\n' % (msg,repr(v))) - if isstring(vars[n]) and type(params[n]) is type(0): + if isstring(vars[n]) and isinstance(params[n], int): params[n] = chr(params[n]) nl = n.lower() if nl!=n: @@ -2458,14 +2458,15 @@ determineexprtype_re_3 = re.compile(r'\A[+-]?[\d.]+[\d+-de.]*(_(P<name>[\w]+)|)\ determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z',re.I) determineexprtype_re_5 = re.compile(r'\A(?P<name>\w+)\s*\(.*?\)\s*\Z',re.I) def _ensure_exprdict(r): - if type(r) is type(0): + if isinstance(r, int): return {'typespec':'integer'} - if type(r) is type(0.0): + if isinstance(r, float): return {'typespec':'real'} - if type(r) is type(0j): + if isinstance(r, complex): return {'typespec':'complex'} - assert type(r) is type({}),repr(r) - return r + if isinstance(r, dict): + return r + raise AssertionError(repr(r)) def determineexprtype(expr,vars,rules={}): if expr in vars: diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index 98f58e333..64c13fff0 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -339,7 +339,7 @@ def dict_append(d_out,d_in): for (k,v) in d_in.items(): if k not in d_out: d_out[k] = [] - if type(v) is list: + if isinstance(v, list): d_out[k] = d_out[k] + v else: d_out[k].append(v) diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py index b68a79b64..7e25a4930 100644 --- a/numpy/f2py/f90mod_rules.py +++ b/numpy/f2py/f90mod_rules.py @@ -119,7 +119,7 @@ def buildhooks(pymod): dadd('\\subsection{Fortran 90/95 module \\texttt{%s}}\n'%(m['name'])) if hasnote(m): note = m['note'] - if type(note) is type([]): note='\n'.join(note) + if isinstance(note, list): note='\n'.join(note) dadd(note) if onlyvars: dadd('\\begin{description}') @@ -145,7 +145,7 @@ def buildhooks(pymod): dadd('\\item[]{{}\\verb@%s@{}}'%(capi_maps.getarrdocsign(n,var))) if hasnote(var): note = var['note'] - if type(note) is type([]): note='\n'.join(note) + if isinstance(note, list): note='\n'.join(note) dadd('--- %s'%(note)) if isallocatable(var): fargs.append('f2py_%s_getdims_%s'%(m['name'],n)) diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py index a76401ac9..f7f82fc99 100644 --- a/numpy/f2py/rules.py +++ b/numpy/f2py/rules.py @@ -1388,9 +1388,9 @@ def buildapi(rout): vrd['check']=c ar=applyrules(check_rules,vrd,var[a]) rd=dictappend(rd,ar) - if type(rd['cleanupfrompyobj']) is list: + if isinstance(rd['cleanupfrompyobj'], list): rd['cleanupfrompyobj'].reverse() - if type(rd['closepyobjfrom']) is list: + if isinstance(rd['closepyobjfrom'], list): rd['closepyobjfrom'].reverse() rd['docsignature']=stripcomma(replace('#docsign##docsignopt##docsignxa#', {'docsign':rd['docsign'], @@ -1415,15 +1415,15 @@ def buildapi(rout): else: rd['callcompaqfortran']=cfs rd['callfortran']=cfs - if type(rd['docreturn'])==list: + if isinstance(rd['docreturn'], list): rd['docreturn']=stripcomma(replace('#docreturn#',{'docreturn':rd['docreturn']}))+' = ' rd['docstrsigns']=[] rd['latexdocstrsigns']=[] for k in ['docstrreq','docstropt','docstrout','docstrcbs']: - if k in rd and type(rd[k])==list: + if k in rd and isinstance(rd[k], list): rd['docstrsigns']=rd['docstrsigns']+rd[k] k='latex'+k - if k in rd and type(rd[k])==list: + if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns']=rd['latexdocstrsigns']+rd[k][0:1]+\ ['\\begin{description}']+rd[k][1:]+\ ['\\end{description}'] diff --git a/numpy/lib/arrayterator.py b/numpy/lib/arrayterator.py index 094d41c11..c2cde574e 100644 --- a/numpy/lib/arrayterator.py +++ b/numpy/lib/arrayterator.py @@ -188,7 +188,7 @@ class Arrayterator(object): step = self.step[:] ndims = len(self.var.shape) - while 1: + while True: count = self.buf_size or reduce(mul, self.shape) # iterate over each dimension, looking for the diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 40788e148..81e8cd010 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -344,8 +344,7 @@ def read_array_header_1_0(fp): if not isinstance(d, dict): msg = "Header is not a dictionary: %r" raise ValueError(msg % d) - keys = list(d.keys()) - keys.sort() + keys = sorted(d.keys()) if keys != ['descr', 'fortran_order', 'shape']: msg = "Header does not contain the correct keys: %r" raise ValueError(msg % (keys,)) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 1ead53c87..a7163a7ca 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1273,8 +1273,7 @@ def unique(x): idx = concatenate(([True],tmp[1:]!=tmp[:-1])) return tmp[idx] except AttributeError: - items = list(set(x)) - items.sort() + items = sorted(set(x)) return asarray(items) def extract(condition, arr): diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 314cba120..b3c9b72bc 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -244,7 +244,7 @@ class AxisConcatenator(object): frame = sys._getframe().f_back mymat = matrix.bmat(key,frame.f_globals,frame.f_locals) return mymat - if type(key) is not tuple: + if not isinstance(key, tuple): key = (key,) objs = [] scalars = [] @@ -252,7 +252,7 @@ class AxisConcatenator(object): scalartypes = [] for k in range(len(key)): scalar = False - if type(key[k]) is slice: + if isinstance(key[k], slice): step = key[k].step start = key[k].start stop = key[k].stop @@ -627,7 +627,7 @@ class IndexExpression(object): self.maketuple = maketuple def __getitem__(self, item): - if self.maketuple and type(item) != tuple: + if self.maketuple and not isinstance(item, tuple): return (item,) else: return item diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index c13c7e94a..fbcb5a46e 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1025,7 +1025,7 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = asstr(delimiter).join(map(asstr, fmt)) - elif type(fmt) is str: + elif isinstance(fmt, str): n_fmt_chars = fmt.count('%') error = ValueError('fmt has wrong number of %% formats: %s' % fmt) if n_fmt_chars == 1: diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index e61a89b87..5402adc6d 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -905,7 +905,7 @@ def _raise_power(astr, wrap=70): line1 = '' line2 = '' output = ' ' - while 1: + while True: mat = _poly_mat.search(astr, n) if mat is None: break diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index de8606167..5357c62df 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -643,10 +643,9 @@ def get_array_prepare(*args): In case of ties, leftmost wins. If no wrapper is found, return None """ - wrappers = [(getattr(x, '__array_priority__', 0), -i, + wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_prepare__) for i, x in enumerate(args) - if hasattr(x, '__array_prepare__')] - wrappers.sort() + if hasattr(x, '__array_prepare__')) if wrappers: return wrappers[-1][-1] return None @@ -656,10 +655,9 @@ def get_array_wrap(*args): In case of ties, leftmost wins. If no wrapper is found, return None """ - wrappers = [(getattr(x, '__array_priority__', 0), -i, + wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_wrap__) for i, x in enumerate(args) - if hasattr(x, '__array_wrap__')] - wrappers.sort() + if hasattr(x, '__array_wrap__')) if wrappers: return wrappers[-1][-1] return None diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 6e0cfcddb..cb9b6ee49 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -58,7 +58,7 @@ def mintypecode(typechars,typeset='GDFgdf',default='d'): 'G' """ - typecodes = [(type(t) is type('') and t) or asarray(t).dtype.char\ + typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char\ for t in typechars] intersection = [t for t in typecodes if t in typeset] if not intersection: diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 2519cd4d4..f94abeeab 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -435,7 +435,7 @@ def _makenamedict(module='numpy'): thedict = {module.__name__:module.__dict__} dictlist = [module.__name__] totraverse = [module.__dict__] - while 1: + while True: if len(totraverse) == 0: break thisdict = totraverse.pop(0) @@ -584,7 +584,7 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None") print(" %s -- %s" % (meth, methstr), file=output) - elif type(object) is types.InstanceType: ## check for __call__ method + elif isinstance(object, types.InstanceType): ## check for __call__ method print("Instance of class: ", object.__class__.__name__, file=output) print(file=output) if hasattr(object, '__call__'): diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py index f8471f965..4a517d531 100644 --- a/numpy/linalg/lapack_lite/clapack_scrub.py +++ b/numpy/linalg/lapack_lite/clapack_scrub.py @@ -32,7 +32,7 @@ def runScanner(data, scanner_class, lexicon=None): scanner = scanner_class(lexicon, info) else: scanner = scanner_class(info) - while 1: + while True: value, text = scanner.read() if value is None: break diff --git a/numpy/linalg/lapack_lite/make_lite.py b/numpy/linalg/lapack_lite/make_lite.py index 66171ba85..6aa5c3e80 100755 --- a/numpy/linalg/lapack_lite/make_lite.py +++ b/numpy/linalg/lapack_lite/make_lite.py @@ -126,7 +126,7 @@ class FortranLibrary(object): """ done_this = set() last_todo = set() - while 1: + while True: todo = set(self.allRoutineNames()) - done_this if todo == last_todo: break @@ -151,8 +151,7 @@ class LapackLibrary(FortranLibrary): return routine def allRoutinesByType(self, typename): - routines = [(r.name,r) for r in self.allRoutines() if r.type == typename] - routines.sort() + routines = sorted((r.name,r) for r in self.allRoutines() if r.type == typename) return [a[1] for a in routines] def printRoutineNames(desc, routines): diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index 861fefad0..2f3159c49 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -1435,14 +1435,14 @@ class MAxisConcatenator(AxisConcatenator): def __getitem__(self, key): if isinstance(key, str): raise MAError("Unavailable for masked array.") - if type(key) is not tuple: + if not isinstance(key, tuple): key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False - if type(key[k]) is slice: + if isinstance(key[k], slice): step = key[k].step start = key[k].start stop = key[k].stop @@ -1450,12 +1450,12 @@ class MAxisConcatenator(AxisConcatenator): start = 0 if step is None: step = 1 - if type(step) is type(1j): + if isinstance(step, complex): size = int(abs(step)) newobj = np.linspace(start, stop, num=size) else: newobj = np.arange(start, stop, step) - elif type(key[k]) is str: + elif isinstance(key[k], str): if (key[k] in 'rc'): self.matrix = True self.col = (key[k] == 'c') diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py index 4c5b7e9fc..a80a5ae3c 100644 --- a/numpy/numarray/alter_code1.py +++ b/numpy/numarray/alter_code1.py @@ -81,7 +81,7 @@ def changeimports(fstr, name, newname): ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) - while 1: + while True: found = fstr.find(fromstr,ind) if (found < 0): break diff --git a/numpy/numarray/functions.py b/numpy/numarray/functions.py index 3f91046d2..78d05e5f5 100644 --- a/numpy/numarray/functions.py +++ b/numpy/numarray/functions.py @@ -222,7 +222,7 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, buf = np.newbuffer(initsize) bytesread=0 - while 1: + while True: data=infile.read(blocksize) if len(data) != blocksize: ##eof break diff --git a/numpy/numarray/session.py b/numpy/numarray/session.py index f1dcbfbdc..e40cd4033 100644 --- a/numpy/numarray/session.py +++ b/numpy/numarray/session.py @@ -120,7 +120,7 @@ def _callers_modules(): g = _callers_globals() mods = [] for k,v in g.items(): - if type(v) == type(sys): + if isinstance(v, type(sys)): mods.append(getattr(v,"__name__")) return mods @@ -326,7 +326,7 @@ def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): dictionary = _callers_globals() values = [] p = pickle.Unpickler(file) - while 1: + while True: o = p.load() if isinstance(o, _SaveSession): session = dict(zip(o.keys, values)) diff --git a/numpy/oldnumeric/alter_code1.py b/numpy/oldnumeric/alter_code1.py index 1e84fd894..34a59a7ca 100644 --- a/numpy/oldnumeric/alter_code1.py +++ b/numpy/oldnumeric/alter_code1.py @@ -88,7 +88,7 @@ def changeimports(fstr, name, newname): ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) - while 1: + while True: found = fstr.find(fromstr,ind) if (found < 0): break diff --git a/numpy/oldnumeric/alter_code2.py b/numpy/oldnumeric/alter_code2.py index 4e4d94cd6..c163c9565 100644 --- a/numpy/oldnumeric/alter_code2.py +++ b/numpy/oldnumeric/alter_code2.py @@ -54,7 +54,7 @@ def changeimports(fstr, name, newname): ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) - while 1: + while True: found = fstr.find(fromstr,ind) if (found < 0): break diff --git a/numpy/oldnumeric/fix_default_axis.py b/numpy/oldnumeric/fix_default_axis.py index 57ab3ce78..5f6128724 100644 --- a/numpy/oldnumeric/fix_default_axis.py +++ b/numpy/oldnumeric/fix_default_axis.py @@ -185,7 +185,7 @@ def _import_change(fstr, names): ind = 0 importstr = "from numpy import" N = len(importstr) - while 1: + while True: ind = fstr.find(importstr, ind) if (ind < 0): break diff --git a/tools/c_coverage/c_coverage_report.py b/tools/c_coverage/c_coverage_report.py index d1084b75e..d9eb49739 100755 --- a/tools/c_coverage/c_coverage_report.py +++ b/tools/c_coverage/c_coverage_report.py @@ -110,8 +110,7 @@ class SourceFiles: fd = open(os.path.join(root, 'index.html'), 'w') fd.write("<html>") - paths = list(self.files.keys()) - paths.sort() + paths = sorted(self.files.keys()) for path in paths: fd.write('<p><a href="%s.html">%s</a></p>' % (self.clean_path(path), escape(path[len(self.prefix):]))) |