Suppose my python code branches based on the result of a try/except as follows:
def(x):
no_errors = False
try:
y = f(x)
no_errors = True
except ZError:
no_errors = False
if no_errors:
do_stuff(y)
else:
do_other_stuff(x)
My linter warns that y may be undefined. Is this poor practice? What is the recommended fix?
Typically, you wouldn't have code structured like this. You'd have else
and/or finally
clauses in the try
statement.
def f(x):
try:
y = f(x)
except ZError:
do_other_stuff(x)
else:
do_stuff(y)
y
will be undefined if y = f(x)
throws any kind of exception that is not a ZError
. Technically, the variable no_errors
really means "no ZError
s". You could handle this more elegantly using an else
or finally
block to define y
.
For example:
def(x):
no_errors = false
try:
y = f(x)
no_errors = True
except ZError:
no_errors = False
finally:
y = some_default
if no_errors:
do_stuff(y)
else:
do_other_stuff(x)
Also, the bool is not needed, since you can simply leverage the conditional nature of the try / except blocks (see chepner's answer)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.