pythonpython-ostilde-expansion

Way to Perform Tilde-Expansion on Every Path Evaluated by Python OS Module?


I'm running Linux, and would like for my project to replace the tilde character, '~', at the beginning of a path with my home directory, in the same way the terminal does. I've found a method of the os module that achieves this, known as os.path.expanduser().

from os.path import expanduser


# '/home/user/Music/Playlist 04'
expanduser('~/Music/Playlist 04')

My problem is that my project is going to incorporate many, many different packages that are completely separate from one another, meaning if I want to implement this functionality then I have to call the expanduser() method on every single path I take in for every single package.

Is there some kind of function I can call in my main file, the one that will run the main loop and make use of all of my other packages, that will somehow make it a rule that all file paths evaluated by the 'os' module by subjected to the expanduser() method? Is there a way of doing this other than the expanduser() method? Would I have to hack os?

My two main reasons for wanting to implement this functionality are as follows.

Thanks in advance.


Solution

  • While it's technically possible, it's generally considered a bad practice because it will make your code harder to maintain, understand, and debug. You likely won't find a way to do this reliably.

    I would strongly recommend against this approach in most cases, especially if there are other clearer ways to achieve your goals. Monkey patching should be used as a last resort, and even then, used very carefully.

    If this is really a problem for you then I would recommend reconsidering your application's design.

    Are there really that many different code paths in your application that accept user input?