Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't write try-else without except in python

Tags:

python

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:
    ...
like image 801
Ariakenom Avatar asked Sep 05 '25 03:09

Ariakenom


2 Answers

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:
    ...
like image 146
Bibhav Avatar answered Sep 07 '25 19:09

Bibhav


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
  
like image 32
Ariakenom Avatar answered Sep 07 '25 20:09

Ariakenom