PeetRonics' blog

All can be true!

Thu 14 November 2019 - read time: 2 min.

What I Have Learned Today - #010

  

code snippet

I was fed up with all the hard-coded paths in our code repository (Python). Thought there must be a better, more elegant way. And it appears there is.

Today I learned about os.path.realpath(path). This function resolves the full path of the specified file or directory, based on the path from where your script is run. An example implementation:

import os.path

resource_directory = os.path.realpath("output")
print(resource_directory)

# >>> C:\git_repos\01_Private_Projects\Python_snippets\output

Currently I’m going through our codebase and see where we can replace hard coded paths with the os.path.realpath function. Neat! Full documentation on this function and the whole os.path module can be found here.

Bonus tip: In the code snippet above you can see I only import os.path and not the whole os module. In Python is good practice only to import what you need. Import more can pollute the namespace and can cause confusion and conflicts. Never ever do import * from blah !!!

Conclusion

It is worth solving bug-bears. In this example, code-base. Doing so will expand the knowledge of the thing you are working on/with.

This post is part of a series of articles about “What I Have Learned Today”; acknowledging every day the thing I have learned. Feel free to read the other posts. all opinions in this article are my own and not necessarily represent the views of my employer.