Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify a behavior of `pathlib.Path`?

I want pathlib.Path to automatically output logs for some destructive commands such as path.rename(new_path).

I made a subclass of pathlib.Path with logging functions, and replaced from pathlib import Path to from mylib import MyPath as Path.
But it does not affect to the existing subclasses of pathlib.Path such as pathlib.WindowsPath, which is the actual implementation class of path instances.

from pathlib import Path
from mynicelib import MyPath

p = MyPath('/path/to/file')

isinstance(p, MyPath)  # -> False
isinstance(p, Path)  # -> True
type(p)  # -> <class 'pathlib.WindowsPath'>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just do some monkeypatching:

from pathlib import Path

Path.oldrename = Path.rename

def rename(self,b):
    print("Inside my rename")
    self.oldrename(b)

Path.rename = rename

p = Path('./x.c')
p.rename('y.c')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading