Python - Loops and Exception Block Else Statements#
The try/except block has an option else clause. That else
clause is executed if an exception is not raised in the block. Loops, also have an else clause. I never thought that I would actually need to use those and thought they were superfluous. Today, I used both. In the following code, I wanted to create a folder, but wanted to make sure that I didn’t create a duplicate folder (i.e. I didn’t want to write files into the same folder).
Consider this code:
1from pathlib import Path
2
3def construct_non_duplicate_folder(root:Path, target:str) -> Path:
4 folder = root / Path(target)
5
6 for i in range(25):
7
8 try:
9 folder.mkdir(parents=True, exist_ok=False)
10
11 except FileExistsError as fe:
12 folder = root / Path(f'{target} ({i})')
13
14 else:
15 break
16
17 else:
18 raise FileExistsError(f'The folder {folder} exists!')
19
20 return folder
In the try/except
block (line 14) I have an else statement that breaks the loop. That is, it found a name that didn’t conflict with an existing one. Essentially, if it finds a folder name that doesn’t exist, it breaks out of the loop; the loop ends early.
I an else block tied to the for
loop (line 17) that will only execute if the for loop runs to completion. If it does, an exception is raised indicating that the folder already exists and there are 26 variations of it already.
This is a very interesting approach and a lot simpler than a bunch of if statements. What we have is a nice mechanism to retry different procedural folder names with a reasonable limit in place. This approach could be applied to file names as well.