Recursing function to create dir in python I am trying to write a small function to safely create dir until dir until full path of file exists. I'm trying to do it in a recursing function and would love to get some feedback.

def makedir(filepath: str) -&gt; bool:
    if os.path.exists(os.path.dirname(filepath)):
        return
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    makedir(filepath)

makedir('/a/b/c/d/x.text')
#should create a then b then c then d
makedir('/a/b/c/e/y.text')
#should create e only since a, b,c already exist
First, os.makedirs already creates all the intermediate directories in the path. That is its job. So there is no need to use recursion.

There is also no need to use os.path.exists, because you are using the exist_ok=True argument with os.makedirs. This means that os.makedirs will not error out if the directory already exists.*

Your type hint for the return type should be None, since you are not returning any values.

I would also change the name of your function. I think the name makedir is too close to os.makedirs, which is confusing.

import os

def makedirs_for_file(filepath: str) -&gt; None:
    os.makedirs(os.path.dirname(filepath), exist_ok=True)




*Unless you are using a Python version before 3.4.1. In this case, os.makedirs may still error out, depending on the mode of the existing directory. See the documentation for more details.