Search code examples
pythonpathpathlib

pathlib Path - create path instance and mkdir in one line


Pathlib Path - looks like I cannot 'create a path instance' and 'mkdir' in one one line? Am I doing something wrong or this is not possible?

This returns None for region_path. WHY?

script_path = Path(__file__).parent.resolve()
region_path = Path(script_path/"device_details"/"region").mkdir(parents=True, exist_ok=True)

This returns a valid path for region_path, but I'm bothered by the extra step/line.

script_path = Path(__file__).parent.resolve()
region_path = Path(script_path/"device_details"/"region")
region_path.mkdir(parents=True, exist_ok=True)


Solution

  • This returns None for region_path. WHY?

    Because, Path.mkdir() doesn't return anything.

    this is not possible?

    It is possible:

    from pathlib import Path
    
    (region_path := (script_path := Path(__file__).parent.resolve()) / "device_details" / "region").mkdir(parents=True, exist_ok=True)
    

    But it seems like an abuse of the walrus operator so I would stick to the way you are doing it. As the Zen of Python says:

    Simple is better than complex.

    Readability counts.