Skip to content

Commit

Permalink
substitute bare 'except' clauses by 'except Exception' or more specif…
Browse files Browse the repository at this point in the history
…ic where it's obvious
  • Loading branch information
leogama committed Jun 21, 2022
1 parent bc87125 commit 1f8db14
Show file tree
Hide file tree
Showing 11 changed files with 40 additions and 44 deletions.
7 changes: 2 additions & 5 deletions dill/__diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
try:
import numpy
HAS_NUMPY = True
except:
except ImportError:
HAS_NUMPY = False

# pypy doesn't use reference counting
Expand All @@ -38,10 +38,7 @@ def get_attrs(obj):
if type(obj) in builtins_types \
or type(obj) is type and obj in builtins_types:
return
try:
return obj.__dict__
except:
return
return getattr(obj, '__dict__', None)


def get_seq(obj, cache={str: False, frozenset: False, list: True, set: True,
Expand Down
27 changes: 13 additions & 14 deletions dill/_dill.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,7 +631,7 @@ def use_diff(on=True):
if _use_diff and diff is None:
try:
from . import diff as d
except:
except ImportError:
import diff as d
diff = d

Expand Down Expand Up @@ -697,7 +697,7 @@ def _create_typemap():
try:
import symtable
_incedental_reverse_typemap["SymtableStentryType"] = type(symtable.symtable("", "string", "exec")._table)
except:
except ImportError:
pass

if sys.hexversion >= 0x30a00a0:
Expand All @@ -711,7 +711,7 @@ def _create_typemap():
try:
import winreg
_incedental_reverse_typemap["HKEYType"] = winreg.HKEYType
except:
except ImportError:
pass

_reverse_typemap.update(_incedental_reverse_typemap)
Expand Down Expand Up @@ -941,7 +941,7 @@ def _create_filehandle(name, mode, position, closed, open, strictio, fmode, fdat
else:
try:
exists = os.path.exists(name)
except:
except Exception:
exists = False
if not exists:
if strictio:
Expand Down Expand Up @@ -1043,7 +1043,7 @@ def __ror__(self, a):
# mapping referenced by the proxy. It may work for other implementations,
# but is not guaranteed.
MAPPING_PROXY_TRICK = __d is (DictProxyType(__d) | _dictproxy_helper_instance)
except:
except Exception:
MAPPING_PROXY_TRICK = False
del __d

Expand Down Expand Up @@ -1108,15 +1108,15 @@ def _create_capsule(pointer, name, context, destructor):
names = uname.rsplit('.', i)
try:
module = __import__(names[0])
except:
except ImportError:
pass
obj = module
for attr in names[1:]:
obj = getattr(obj, attr)
capsule = obj
attr_found = True
break
except:
except Exception:
pass

if attr_found:
Expand All @@ -1134,14 +1134,14 @@ def _getattr(objclass, name, repr_str):
try: #XXX: works only for __builtin__ ?
attr = repr_str.split("'")[3]
return eval(attr+'.__dict__["'+name+'"]')
except:
except Exception:
try:
attr = objclass.__dict__
if type(attr) is DictProxyType:
attr = attr[name]
else:
attr = getattr(objclass,name)
except:
except (AttributeError, KeyError):
attr = getattr(objclass,name)
return attr

Expand Down Expand Up @@ -1194,7 +1194,7 @@ def _locate_function(obj, pickler=None):
try:
found, _ = _getattribute(module, obj.__qualname__)
return found is obj
except:
except AttributeError:
return False
else:
found = _import_module(module_name + '.' + obj.__name__, safe=True)
Expand Down Expand Up @@ -1595,7 +1595,7 @@ def save_wrapper_descriptor(pickler, obj):
def save_cell(pickler, obj):
try:
f = obj.cell_contents
except:
except ValueError:
log.info("Ce3: %s" % obj)
# _shims._CELL_EMPTY is defined in _shims.py to support PyPy 2.7.
# It unpickles to a sentinel object _dill._CELL_EMPTY, also created in
Expand Down Expand Up @@ -1902,7 +1902,7 @@ def save_function(pickler, obj):
found, _ = _getattribute(module, obj.__qualname__)
if getattr(found, '__func__', None) is obj:
_pypy_builtin = True
except:
except AttributeError:
pass

if _pypy_builtin:
Expand Down Expand Up @@ -2142,9 +2142,8 @@ def _extend():
for t,func in Pickler.dispatch.items():
try:
StockPickler.dispatch[t] = func
except: #TypeError, PicklingError, UnpicklingError
except Exception: #TypeError, PicklingError, UnpicklingError
log.info("skip: %s" % t)
else: pass
return

del diff, _use_diff, use_diff
Expand Down
4 changes: 2 additions & 2 deletions dill/_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class _newclass2(object):
def _function(x): yield x
def _function2():
try: raise
except:
except Exception:
from sys import exc_info
e, er, tb = exc_info()
return er, tb
Expand Down Expand Up @@ -379,7 +379,7 @@ class _Struct(ctypes.Structure):
try:
import symtable
a["SymtableEntryType"] = symtable.symtable("", "string", "exec")._table
except:
except ImportError:
pass

if sys.hexversion >= 0x30a00a0:
Expand Down
8 changes: 4 additions & 4 deletions dill/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def outermost(func): # is analogous to getsource(func,enclosing=True)
# get the enclosing source
from .source import getsourcelines
try: lines,lnum = getsourcelines(func, enclosing=True)
except: #TypeError, IOError
except Exception: #TypeError, IOError
lines,lnum = [],None
code = ''.join(lines)
# get all possible names,objects that are named in the enclosing source
Expand All @@ -53,7 +53,7 @@ def outermost(func): # is analogous to getsource(func,enclosing=True)
for name,obj in _locals: #XXX: don't really need 'name'
try:
if getsourcelines(obj) == (lines,lnum): return obj
except: #TypeError, IOError
except Exception: #TypeError, IOError
pass
return #XXX: or raise? no matches

Expand Down Expand Up @@ -137,7 +137,7 @@ def get_cell_contents():
for (name,c) in zip(func,closures):
try:
cell_contents = c.cell_contents
except:
except ValueError:
continue
yield (name,c.cell_contents)

Expand Down Expand Up @@ -186,7 +186,7 @@ def globalvars(func, recurse=True, builtin=False):
for obj in getattr(orig_func, func_closure) or {}:
try:
cell_contents = obj.cell_contents
except:
except ValueError:
pass
else:
_vars = globalvars(cell_contents, recurse, builtin) or {}
Expand Down
22 changes: 11 additions & 11 deletions dill/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _matchlambda(func, line):
lhs,rhs = line.split('lambda ',1)[-1].split(":", 1) #FIXME: if !1 inputs
try: #FIXME: unsafe
_ = eval("lambda %s : %s" % (lhs,rhs), globals(),locals())
except: _ = dummy
except Exception: _ = dummy
# get code objects, for comparison
_, code = getcode(_).co_code, getcode(func).co_code
# check if func is in closure
Expand All @@ -78,7 +78,7 @@ def _matchlambda(func, line):
_lhs,_rhs = rhs.split('lambda ',1)[-1].split(":",1) #FIXME: if !1 inputs
try: #FIXME: unsafe
_f = eval("lambda %s : %s" % (_lhs,_rhs), globals(),locals())
except: _f = dummy
except Exception: _f = dummy
# get code objects, for comparison
_, code = getcode(_f).co_code, getcode(func).co_code
if len(_) != len(code): return False
Expand Down Expand Up @@ -118,7 +118,7 @@ def findsource(object):
try:
import readline
err = ''
except:
except ImportError:
import sys
err = sys.exc_info()[1].args[0]
if sys.platform[:3] == 'win':
Expand Down Expand Up @@ -514,7 +514,7 @@ def func(*args, **kwds):
try:
# _ = eval(getsource(f, force=True)) #XXX: safer but less robust
exec(getimportable(f, alias='_'), __globals__, __locals__)
except:
except Exception:
raise ImportError('cannot import name ' + f.__name__)
return _(*args, **kwds)
func.__name__ = f.__name__
Expand Down Expand Up @@ -624,7 +624,7 @@ def _namespace(obj):
if module in ['builtins','__builtin__']: # BuiltinFunctionType
if _intypes(name): return ['types'] + [name]
return qual + [name] #XXX: can be wrong for some aliased objects
except: pass
except Exception: pass
# special case: numpy.inf and numpy.nan (we don't want them as floats)
if str(obj) in ['inf','nan','Inf','NaN']: # is more, but are they needed?
return ['numpy'] + [str(obj)]
Expand Down Expand Up @@ -712,7 +712,7 @@ def getimport(obj, alias='', verify=True, builtin=False, enclosing=False):
try: # look for '<...>' and be mindful it might be in lists, dicts, etc...
name = repr(obj).split('<',1)[1].split('>',1)[1]
name = None # we have a 'object'-style repr
except: # it's probably something 'importable'
except Exception: # it's probably something 'importable'
if head in ['builtins','__builtin__']:
name = repr(obj) #XXX: catch [1,2], (1,2), set([1,2])... others?
else:
Expand Down Expand Up @@ -770,7 +770,7 @@ def _importable(obj, alias='', source=None, enclosing=False, force=True, \
try:
return getsource(obj, alias, enclosing=enclosing, \
force=force, lstrip=lstrip, builtin=builtin)
except: pass
except Exception: pass
try:
if not _isinstance(obj):
return getimport(obj, alias, enclosing=enclosing, \
Expand All @@ -785,12 +785,12 @@ def _importable(obj, alias='', source=None, enclosing=False, force=True, \
if alias == name: _alias = ""
return _import+_alias+"%s\n" % name

except: pass
except Exception: pass
if not source: # try getsource, only if it hasn't been tried yet
try:
return getsource(obj, alias, enclosing=enclosing, \
force=force, lstrip=lstrip, builtin=builtin)
except: pass
except Exception: pass
# get the name (of functions, lambdas, and classes)
# or hope that obj can be built from the __repr__
#XXX: what to do about class instances and such?
Expand Down Expand Up @@ -930,7 +930,7 @@ def importable(obj, alias='', source=None, builtin=True):
if len(src) > 1:
raise NotImplementedError('not implemented')
return list(src.values())[0]
except:
except Exception:
if tried_source: raise
tried_import = True
# we want the source
Expand Down Expand Up @@ -969,7 +969,7 @@ def _code_stitcher(block):
if not obj: return src
if not src: return obj
return obj + src
except:
except Exception:
if tried_import: raise
tried_source = True
source = not source
Expand Down
2 changes: 1 addition & 1 deletion tests/test_extendpickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def test_isdill():
pickler = mp.reduction.ForkingPickler(obj_io)
assert pickle._dill.is_dill(pickler, child=True) is True
assert pickle._dill.is_dill(pickler, child=False) is False
except:
except Exception:
pass


Expand Down
2 changes: 1 addition & 1 deletion tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def test_functions():
assert 'empty' in str(cell_copy.__closure__[0])
try:
cell_copy()
except:
except Exception:
# this is good
pass
else:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_nested.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def test_pickled_inner():
def test_moduledict_where_not_main():
try:
from . import test_moduledict
except:
except ImportError:
import test_moduledict
name = 'test_moduledict.py'
if os.path.exists(name) and os.path.exists(name+'c'):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_recursive.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def copy(obj, byref=False, recurse=False):
if byref:
try:
return dill.copy(obj, byref=byref, recurse=recurse)
except:
except Exception:
pass
else:
raise AssertionError('Copy of %s with byref=True should have given a warning!' % (obj,))
Expand Down Expand Up @@ -144,7 +144,7 @@ def test_recursive_function():
for _fib in (fib3, fib4):
try:
_fib(5)
except:
except Exception:
# This is expected to fail because fib no longer exists
pass
else:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_selected.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_dict_contents():
for i,j in c.items():
#try:
ok = dill.pickles(j)
#except:
#except Exception:
# print ("FAIL: %s with %s" % (i, dill.detect.errors(j)))
if verbose: print ("%s: %s, %s" % (ok, type(j), j))
assert ok
Expand All @@ -29,7 +29,7 @@ def _g(x): yield x;

def _f():
try: raise
except:
except Exception:
from sys import exc_info
e, er, tb = exc_info()
return er, tb
Expand Down
2 changes: 1 addition & 1 deletion tests/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def test_dictproxy():
from dill._dill import DictProxyType
try:
m = DictProxyType({"foo": "bar"})
except:
except Exception:
m = type.__dict__
mp = dill.copy(m)
assert mp.items() == m.items()
Expand Down

0 comments on commit 1f8db14

Please sign in to comment.