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

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?

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

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

  • I don’t want to have to import and then call the same method in all of my different packages just to avoid hardcoding my user directory. It’s just replacing one bad practice with another.
  • Suppose one day I need to access a directory beginning with the ~? Would I need to go back in and change it? I don’t want to code my own specific preference into everything I do.

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?

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