Skip to content

Fix exception causes all over the codebase #2199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/2199.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix exception causes all over the codebase by using ``raise new_exception from old_exception``
16 changes: 8 additions & 8 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1378,7 +1378,7 @@ def evaluate_marker(text, extra=None):
marker = packaging.markers.Marker(text)
return marker.evaluate()
except packaging.markers.InvalidMarker as e:
raise SyntaxError(e)
raise SyntaxError(e) from e


class NullProvider:
Expand Down Expand Up @@ -2288,8 +2288,8 @@ def declare_namespace(packageName):
__import__(parent)
try:
path = sys.modules[parent].__path__
except AttributeError:
raise TypeError("Not a package:", parent)
except AttributeError as e:
raise TypeError("Not a package:", parent) from e

# Track what packages are namespaces, so when new path items are added,
# they can be updated
Expand Down Expand Up @@ -2469,7 +2469,7 @@ def resolve(self):
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc))
raise ImportError(str(exc)) from exc

def require(self, env=None, installer=None):
if self.extras and not self.dist:
Expand Down Expand Up @@ -2689,14 +2689,14 @@ def _warn_legacy_version(self):
def version(self):
try:
return self._version
except AttributeError:
except AttributeError as e:
version = self._get_version()
if version is None:
path = self._get_metadata_path_for_display(self.PKG_INFO)
msg = (
"Missing 'Version:' header and/or {} file at path: {}"
).format(self.PKG_INFO, path)
raise ValueError(msg, self)
raise ValueError(msg, self) from e

return version

Expand Down Expand Up @@ -2749,10 +2749,10 @@ def requires(self, extras=()):
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
except KeyError as e:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
)
) from e
return deps

def _get_metadata_path_for_display(self, name):
Expand Down
4 changes: 2 additions & 2 deletions setuptools/archive_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,10 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
"""
try:
tarobj = tarfile.open(filename)
except tarfile.TarError:
except tarfile.TarError as e:
raise UnrecognizedFormat(
"%s is not a compressed or uncompressed tar file" % (filename,)
)
) from e
with contextlib.closing(tarobj):
# don't do any chowning!
tarobj.chown = lambda *args: None
Expand Down
14 changes: 9 additions & 5 deletions setuptools/command/easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,10 @@ def finalize_options(self):
self.optimize = int(self.optimize)
if not (0 <= self.optimize <= 2):
raise ValueError
except ValueError:
raise DistutilsOptionError("--optimize must be 0, 1, or 2")
except ValueError as e:
raise DistutilsOptionError(
"--optimize must be 0, 1, or 2"
) from e

if self.editable and not self.build_directory:
raise DistutilsArgError(
Expand Down Expand Up @@ -757,9 +759,9 @@ def process_distribution(self, requirement, dist, deps=True, *info):
[requirement], self.local_index, self.easy_install
)
except DistributionNotFound as e:
raise DistutilsError(str(e))
raise DistutilsError(str(e)) from e
except VersionConflict as e:
raise DistutilsError(e.report())
raise DistutilsError(e.report()) from e
if self.always_copy or self.always_copy_from:
# Force all the relevant distros to be copied or activated
for dist in distros:
Expand Down Expand Up @@ -1148,7 +1150,9 @@ def run_setup(self, setup_script, setup_base, args):
try:
run_setup(setup_script, args)
except SystemExit as v:
raise DistutilsError("Setup script exited with %s" % (v.args[0],))
raise DistutilsError(
"Setup script exited with %s" % (v.args[0],)
) from v

def build_and_install(self, setup_script, setup_base):
args = ['bdist_egg', '--dist-dir']
Expand Down
4 changes: 2 additions & 2 deletions setuptools/command/egg_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,11 @@ def finalize_options(self):
list(
parse_requirements(spec % (self.egg_name, self.egg_version))
)
except ValueError:
except ValueError as e:
raise distutils.errors.DistutilsOptionError(
"Invalid distribution name or version syntax: %s-%s" %
(self.egg_name, self.egg_version)
)
) from e

if self.egg_base is None:
dirs = self.distribution.package_dir
Expand Down
4 changes: 2 additions & 2 deletions setuptools/command/rotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ def finalize_options(self):
raise DistutilsOptionError("Must specify number of files to keep")
try:
self.keep = int(self.keep)
except ValueError:
raise DistutilsOptionError("--keep must be an integer")
except ValueError as e:
raise DistutilsOptionError("--keep must be an integer") from e
if isinstance(self.match, six.string_types):
self.match = [
convert_path(p.strip()) for p in self.match.split(',')
Expand Down
5 changes: 3 additions & 2 deletions setuptools/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ def __getattr__(self, attr):
for target in statement.targets
if isinstance(target, ast.Name) and target.id == attr
)
except Exception:
except Exception as e:
raise AttributeError(
"{self.name} has no attribute {attr}".format(**locals()))
"{self.name} has no attribute {attr}".format(**locals())
) from e


@contextlib.contextmanager
Expand Down
38 changes: 21 additions & 17 deletions setuptools/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ def check_importable(dist, attr, value):
try:
ep = pkg_resources.EntryPoint.parse('x=' + value)
assert not ep.extras
except (TypeError, ValueError, AttributeError, AssertionError):
except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
"%r must be importable 'module:attrs' string (got %r)"
% (attr, value)
)
) from e


def assert_string_list(dist, attr, value):
Expand All @@ -219,10 +219,10 @@ def assert_string_list(dist, attr, value):
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError):
except (TypeError, ValueError, AttributeError, AssertionError) as e:
raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
)
) from e


def check_nsp(dist, attr, value):
Expand All @@ -247,12 +247,12 @@ def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError):
except (TypeError, ValueError, AttributeError) as e:
raise DistutilsSetupError(
"'extras_require' must be a dictionary whose values are "
"strings or lists of strings containing valid project/version "
"requirement specifiers."
)
) from e


def _check_extra(extra, reqs):
Expand Down Expand Up @@ -280,7 +280,9 @@ def check_requirements(dist, attr, value):
"{attr!r} must be a string or list of strings "
"containing valid project/version requirement specifiers; {error}"
)
raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
raise DistutilsSetupError(
tmpl.format(attr=attr, error=error)
) from error


def check_specifier(dist, attr, value):
Expand All @@ -292,15 +294,17 @@ def check_specifier(dist, attr, value):
"{attr!r} must be a string "
"containing valid version specifiers; {error}"
)
raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
raise DistutilsSetupError(
tmpl.format(attr=attr, error=error)
) from error


def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError as e:
raise DistutilsSetupError(e)
raise DistutilsSetupError(e) from e


def check_test_suite(dist, attr, value):
Expand Down Expand Up @@ -609,8 +613,8 @@ def _parse_config_files(self, filenames=None):
setattr(self, opt, strtobool(val))
else:
setattr(self, opt, val)
except ValueError as msg:
raise DistutilsOptionError(msg)
except ValueError as e:
raise DistutilsOptionError(e) from e

@staticmethod
def _try_str(val):
Expand Down Expand Up @@ -676,8 +680,8 @@ def _set_command_options(self, command_obj, option_dict=None):
raise DistutilsOptionError(
"error in %s: command '%s' has no such option '%s'"
% (source, command_name, option))
except ValueError as msg:
raise DistutilsOptionError(msg)
except ValueError as e:
raise DistutilsOptionError(e) from e

def parse_config_files(self, filenames=None, ignore_option_errors=False):
"""Parses configuration files from various levels
Expand Down Expand Up @@ -843,10 +847,10 @@ def _exclude_misc(self, name, value):
)
try:
old = getattr(self, name)
except AttributeError:
except AttributeError as e:
raise DistutilsSetupError(
"%s: No such distribution setting" % name
)
) from e
if old is not None and not isinstance(old, sequence):
raise DistutilsSetupError(
name + ": this setting cannot be changed via include/exclude"
Expand All @@ -863,10 +867,10 @@ def _include_misc(self, name, value):
)
try:
old = getattr(self, name)
except AttributeError:
except AttributeError as e:
raise DistutilsSetupError(
"%s: No such distribution setting" % name
)
) from e
if old is None:
setattr(self, name, value)
elif not isinstance(old, sequence):
Expand Down
2 changes: 1 addition & 1 deletion setuptools/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def fetch_build_egg(dist, req):
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as e:
raise DistutilsError(str(e))
raise DistutilsError(str(e)) from e
wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])
dist_location = os.path.join(eggs_dir, wheel.egg_name())
wheel.install_as_egg(dist_location)
Expand Down
2 changes: 1 addition & 1 deletion setuptools/msvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def _msvc14_get_vc_env(plat_spec):
except subprocess.CalledProcessError as exc:
raise distutils.errors.DistutilsPlatformError(
"Error executing {}".format(exc.cmd)
)
) from exc

env = {
key.lower(): value
Expand Down