I want to write something shaped like this this except the invalid_task and work functions are of course written inline.
unfinished_tasks = 0
async def worker(task):
nonlocal unfinished_tasks
unfinished_tasks += 1
try:
if is_invalid(task):
return None
result = work(task)
if is_error(result):
raise Exception()
return result
else:
unfinished_tasks -= 1
But you can't write just:
try:
...
else:
...
You need an except
to write an else
(try-else-finally also doesn't work). The use case for an else
without an except
is to run some code on a non exception exit of the block. There are a few ways to exit a block, like return
, break
, or reaching the end of one of the code paths inside it.
Should python allow try-else without except? Is there a better way to write this?
My current solution is:
try:
...
except None:
raise
else:
...
For this case specifically you can use:
unfinished_tasks = 0
async def worker(task):
nonlocal unfinished_tasks
try:
if is_invalid(task):
return None
result = work(task)
if is_error(result):
raise Exception()
return result
except:
unfinished_tasks += 1
For general cases pass
can be used:
try:
...
except:
pass
else:
...
aneroid correctly pointed out that the code example does not work. The best way to do the thing that I've found is: (But the accepted answer works for me)
unfinished_tasks += 1
was_exception = False
try:
...
except:
was_exception = True
raise
finally:
if not was_exception:
unfinished_tasks -= 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With