pythonwrappermonkeypatchingpathlib

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'>

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')