I have defined a custom function based on pathlib
module in my Python (3.x) script:
def mk_dir(self):
self.mkdir(parents=True,exist_ok=True)
my_path = Path('./1/2/3/')
mk_dir(my_path)
as a shorthand to create a new directory with pathlib.Path.mkdir()
function.
This function will create any missing parents of the given path (parents=True
) and will not raise an error if the directory already exists (exist_ok=True
).
However, I would like to modify my function so it would operate as a chained function, i.e., my_path.mk_dir()
; instead of the traditional method by passing a variable, i.e., mk_dir(my_path)
.
I tried it the following way:
from pathlib import Path
class Path():
def mk_dir(self):
self.mkdir(parents=True,exist_ok=True)
return self
my_path = Path('./1/2/3/')
my_path.mk_dir()
but the best I am getting is this error:
AttributeError: 'WindowsPath' object has no attribute 'mk_dir'
How can one achieve this without changing the module source file itself?
And I am uncertain about these questions:
- Does
class
need to be defined? - Does the function need to return anything?
- And, is it a better practice to check first if the directory exists by
if not my_path.is_dir(): ...
or it is "okay" to use theexist_ok=True
attribute?- I could not conclude this myself, but a related question is here:
- How can I safely create a nested directory in Python?