Skip to content

Commit 990237c

Browse files
authored
Merge pull request #2199 from cool-RR/2020-06-11-raise-from
Fix exception causes all over the codebase
2 parents a877dab + 5f151cb commit 990237c

File tree

10 files changed

+50
-40
lines changed

10 files changed

+50
-40
lines changed

changelog.d/2199.misc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix exception causes all over the codebase by using ``raise new_exception from old_exception``

pkg_resources/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1378,7 +1378,7 @@ def evaluate_marker(text, extra=None):
13781378
marker = packaging.markers.Marker(text)
13791379
return marker.evaluate()
13801380
except packaging.markers.InvalidMarker as e:
1381-
raise SyntaxError(e)
1381+
raise SyntaxError(e) from e
13821382

13831383

13841384
class NullProvider:
@@ -2288,8 +2288,8 @@ def declare_namespace(packageName):
22882288
__import__(parent)
22892289
try:
22902290
path = sys.modules[parent].__path__
2291-
except AttributeError:
2292-
raise TypeError("Not a package:", parent)
2291+
except AttributeError as e:
2292+
raise TypeError("Not a package:", parent) from e
22932293

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

24742474
def require(self, env=None, installer=None):
24752475
if self.extras and not self.dist:
@@ -2689,14 +2689,14 @@ def _warn_legacy_version(self):
26892689
def version(self):
26902690
try:
26912691
return self._version
2692-
except AttributeError:
2692+
except AttributeError as e:
26932693
version = self._get_version()
26942694
if version is None:
26952695
path = self._get_metadata_path_for_display(self.PKG_INFO)
26962696
msg = (
26972697
"Missing 'Version:' header and/or {} file at path: {}"
26982698
).format(self.PKG_INFO, path)
2699-
raise ValueError(msg, self)
2699+
raise ValueError(msg, self) from e
27002700

27012701
return version
27022702

@@ -2749,10 +2749,10 @@ def requires(self, extras=()):
27492749
for ext in extras:
27502750
try:
27512751
deps.extend(dm[safe_extra(ext)])
2752-
except KeyError:
2752+
except KeyError as e:
27532753
raise UnknownExtra(
27542754
"%s has no such extra feature %r" % (self, ext)
2755-
)
2755+
) from e
27562756
return deps
27572757

27582758
def _get_metadata_path_for_display(self, name):

setuptools/archive_util.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,10 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
134134
"""
135135
try:
136136
tarobj = tarfile.open(filename)
137-
except tarfile.TarError:
137+
except tarfile.TarError as e:
138138
raise UnrecognizedFormat(
139139
"%s is not a compressed or uncompressed tar file" % (filename,)
140-
)
140+
) from e
141141
with contextlib.closing(tarobj):
142142
# don't do any chowning!
143143
tarobj.chown = lambda *args: None

setuptools/command/easy_install.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,10 @@ def finalize_options(self):
355355
self.optimize = int(self.optimize)
356356
if not (0 <= self.optimize <= 2):
357357
raise ValueError
358-
except ValueError:
359-
raise DistutilsOptionError("--optimize must be 0, 1, or 2")
358+
except ValueError as e:
359+
raise DistutilsOptionError(
360+
"--optimize must be 0, 1, or 2"
361+
) from e
360362

361363
if self.editable and not self.build_directory:
362364
raise DistutilsArgError(
@@ -757,9 +759,9 @@ def process_distribution(self, requirement, dist, deps=True, *info):
757759
[requirement], self.local_index, self.easy_install
758760
)
759761
except DistributionNotFound as e:
760-
raise DistutilsError(str(e))
762+
raise DistutilsError(str(e)) from e
761763
except VersionConflict as e:
762-
raise DistutilsError(e.report())
764+
raise DistutilsError(e.report()) from e
763765
if self.always_copy or self.always_copy_from:
764766
# Force all the relevant distros to be copied or activated
765767
for dist in distros:
@@ -1148,7 +1150,9 @@ def run_setup(self, setup_script, setup_base, args):
11481150
try:
11491151
run_setup(setup_script, args)
11501152
except SystemExit as v:
1151-
raise DistutilsError("Setup script exited with %s" % (v.args[0],))
1153+
raise DistutilsError(
1154+
"Setup script exited with %s" % (v.args[0],)
1155+
) from v
11521156

11531157
def build_and_install(self, setup_script, setup_base):
11541158
args = ['bdist_egg', '--dist-dir']

setuptools/command/egg_info.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,11 +208,11 @@ def finalize_options(self):
208208
list(
209209
parse_requirements(spec % (self.egg_name, self.egg_version))
210210
)
211-
except ValueError:
211+
except ValueError as e:
212212
raise distutils.errors.DistutilsOptionError(
213213
"Invalid distribution name or version syntax: %s-%s" %
214214
(self.egg_name, self.egg_version)
215-
)
215+
) from e
216216

217217
if self.egg_base is None:
218218
dirs = self.distribution.package_dir

setuptools/command/rotate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ def finalize_options(self):
3636
raise DistutilsOptionError("Must specify number of files to keep")
3737
try:
3838
self.keep = int(self.keep)
39-
except ValueError:
40-
raise DistutilsOptionError("--keep must be an integer")
39+
except ValueError as e:
40+
raise DistutilsOptionError("--keep must be an integer") from e
4141
if isinstance(self.match, six.string_types):
4242
self.match = [
4343
convert_path(p.strip()) for p in self.match.split(',')

setuptools/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ def __getattr__(self, attr):
4242
for target in statement.targets
4343
if isinstance(target, ast.Name) and target.id == attr
4444
)
45-
except Exception:
45+
except Exception as e:
4646
raise AttributeError(
47-
"{self.name} has no attribute {attr}".format(**locals()))
47+
"{self.name} has no attribute {attr}".format(**locals())
48+
) from e
4849

4950

5051
@contextlib.contextmanager

setuptools/dist.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,11 @@ def check_importable(dist, attr, value):
204204
try:
205205
ep = pkg_resources.EntryPoint.parse('x=' + value)
206206
assert not ep.extras
207-
except (TypeError, ValueError, AttributeError, AssertionError):
207+
except (TypeError, ValueError, AttributeError, AssertionError) as e:
208208
raise DistutilsSetupError(
209209
"%r must be importable 'module:attrs' string (got %r)"
210210
% (attr, value)
211-
)
211+
) from e
212212

213213

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

227227

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

257257

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

285287

286288
def check_specifier(dist, attr, value):
@@ -292,15 +294,17 @@ def check_specifier(dist, attr, value):
292294
"{attr!r} must be a string "
293295
"containing valid version specifiers; {error}"
294296
)
295-
raise DistutilsSetupError(tmpl.format(attr=attr, error=error))
297+
raise DistutilsSetupError(
298+
tmpl.format(attr=attr, error=error)
299+
) from error
296300

297301

298302
def check_entry_points(dist, attr, value):
299303
"""Verify that entry_points map is parseable"""
300304
try:
301305
pkg_resources.EntryPoint.parse_map(value)
302306
except ValueError as e:
303-
raise DistutilsSetupError(e)
307+
raise DistutilsSetupError(e) from e
304308

305309

306310
def check_test_suite(dist, attr, value):
@@ -609,8 +613,8 @@ def _parse_config_files(self, filenames=None):
609613
setattr(self, opt, strtobool(val))
610614
else:
611615
setattr(self, opt, val)
612-
except ValueError as msg:
613-
raise DistutilsOptionError(msg)
616+
except ValueError as e:
617+
raise DistutilsOptionError(e) from e
614618

615619
@staticmethod
616620
def _try_str(val):
@@ -676,8 +680,8 @@ def _set_command_options(self, command_obj, option_dict=None):
676680
raise DistutilsOptionError(
677681
"error in %s: command '%s' has no such option '%s'"
678682
% (source, command_name, option))
679-
except ValueError as msg:
680-
raise DistutilsOptionError(msg)
683+
except ValueError as e:
684+
raise DistutilsOptionError(e) from e
681685

682686
def parse_config_files(self, filenames=None, ignore_option_errors=False):
683687
"""Parses configuration files from various levels
@@ -843,10 +847,10 @@ def _exclude_misc(self, name, value):
843847
)
844848
try:
845849
old = getattr(self, name)
846-
except AttributeError:
850+
except AttributeError as e:
847851
raise DistutilsSetupError(
848852
"%s: No such distribution setting" % name
849-
)
853+
) from e
850854
if old is not None and not isinstance(old, sequence):
851855
raise DistutilsSetupError(
852856
name + ": this setting cannot be changed via include/exclude"
@@ -863,10 +867,10 @@ def _include_misc(self, name, value):
863867
)
864868
try:
865869
old = getattr(self, name)
866-
except AttributeError:
870+
except AttributeError as e:
867871
raise DistutilsSetupError(
868872
"%s: No such distribution setting" % name
869-
)
873+
) from e
870874
if old is None:
871875
setattr(self, name, value)
872876
elif not isinstance(old, sequence):

setuptools/installer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def fetch_build_egg(dist, req):
127127
try:
128128
subprocess.check_call(cmd)
129129
except subprocess.CalledProcessError as e:
130-
raise DistutilsError(str(e))
130+
raise DistutilsError(str(e)) from e
131131
wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])
132132
dist_location = os.path.join(eggs_dir, wheel.egg_name())
133133
wheel.install_as_egg(dist_location)

setuptools/msvc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def _msvc14_get_vc_env(plat_spec):
277277
except subprocess.CalledProcessError as exc:
278278
raise distutils.errors.DistutilsPlatformError(
279279
"Error executing {}".format(exc.cmd)
280-
)
280+
) from exc
281281

282282
env = {
283283
key.lower(): value

0 commit comments

Comments
 (0)