0

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:

  1. Does class need to be defined?
  2. Does the function need to return anything?
  3. 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 the exist_ok=True attribute?
Klaidonis
  • 439
  • 1
  • 6
  • 20
  • If you want to override a method, you need to define a subclass. Your `Path` class has nothing to do with `pathlib.Path`, and while it's technically possible, you don't want to monkey patch `pathlib.Path` to change how its `mkdir` function works. – chepner Feb 07 '19 at 20:51
  • However, I don't recommend overriding a method in a way that changes the signature. Define a new method that wraps `mkdir` with your desired arguments. – chepner Feb 07 '19 at 20:53
  • Also, this isn't "function chaining"; it's just method invocation. – chepner Feb 07 '19 at 20:57

0 Answers0