try-except syntax
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Apr 5 22:09:21 EDT 2018
On Thu, 05 Apr 2018 23:04:18 +0200, ElChino wrote:
> I'm trying to simplify a try-except construct. E.g. how come this:
> try:
> _x, pathname, _y = imp.find_module (mod, mod_path)
> return ("%s" % pathname)
imp.find_module is deprecated and should not be used in new code.
Putting that aside, pathname is already a string. Why are you wasting
time interpolating it into a bare "%s" string? Just say `return pathname`.
> except ImportError:
> pass
> except RuntimeError:
> pass
> return ("<unknown>")
Unnecessary parens surrounding a single value.
Possible indentation error. Surely the return "<unknown>" needs to be
indented level with the try/except statements?
> Cannot be simplified into this:
> try:
> _x, pathname, _y = imp.find_module (mod, mod_path) return ("%s" %
> pathname)
> except ImportError:
> except RuntimeError:
> pass
> return ("<unknown>")
>
> Like a "fall-through" in a C-switch statement.
Because fall-through C switch syntax is an abomination, and fortunately
the designer of Python has more sense than to allow that awfulness.
The syntax you are looking for is:
try:
block
except (ImportError, RuntimeError):
block
By the way, RuntimeError is almost never something you want to catch
(except to log before bailing out). It should represent a fatal coding
error, not something safe to ignore.
--
Steve
More information about the Python-list
mailing list