Pro Q
Pro Q

Reputation: 5038

What is the correct type hint for `os.path.dirname`?

When I hover over the function, Pylance tells me the type of the parameter it takes is PathLike[AnyStr@dirname]. What does this mean? Is it just a Union of string and PathLike?

Right now my code looks like this:

def make_path(filename: os.PathLike) -> os.PathLike:
    """
    Ensures that the directory for the given filename exists, creating it if necessary.
    Args:
        filename (os.PathLike): The path to the file for which the directory should be created.
    Returns:
        os.PathLike: The original filename.
    """
    dirname = os.path.dirname(filename)
    if dirname:
        os.makedirs(os.path.dirname(filename), exist_ok=True)

    return filename

But it's giving an error for taking in strings, which didn't happen when I didn't have filename typed.

How can I appropriately type filename in the code above?

Upvotes: 1

Views: 48

Answers (0)

Related Questions