2022-05-22
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:
from pathlib import Path
def construct_non_duplicate_folder(root:Path, target:str) -> Path:
folder = root / Path(target)
for i in range(25):
try:
folder.mkdir(parents=True, exist_ok=False)
except FileExistsError as fe:
folder = root / Path(f'{target} ({i})')
else:
break
else:
raise FileExistsError(f'The folder {folder} exists!')
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.