This function does not actually return anything.
What is good is that you use type hinting for your function. So I was really expecting that you would return a boolean value, because you obviously want some kind of feedback for your request. The problem is that the function makedirs
does not have a return value that you could directly utilize.
So I would approach the problem like this: if an exception occurs, return false otherwise assume everything is alright. Thus the code becomes:
import os, sys
def makedir(filepath: str) -> bool:
try:
if os.path.exists(filepath):
# dir already exists
print(f"FYI Dir already exists: {filepath}")
return False
else:
# attempt to create dir
os.makedirs(filepath)
return True
except (OSError) as e:
# log the details of the exception somewhere (console, file)
print(f"OSError exception occurred while attempting to create directory: {filepath}")
print("Unexpected error:", sys.exc_info()[0])
return False
# testing
ret=makedir('/tmp')
print(f"Return from function: {ret}")
Here I have decided to discard the argument exist_ok=True
and deliberately fail if the directory already exists, because I like to be strict and consider there should be no reason for doing this in the first place, but it's your choice.
I have tried to be as specific as possible and not catch any type of exception. The relevant exception within the scope of this operation is OSError
.
This should suffice, but if necessary you can handle multiple exceptions on the same line like this:
except (OSError, ValueError) as e:
You can also decide to handle the exceptions at module level, anyway the main module should always have its own mechanism to handle exceptions you are not explicitly addressing in specific parts of your code.