Hello python devs.
One thing which appears to be pretty common in many scripts is figuring out module's parent directory path.
HERE = os.path.abspath(os.path.dirname(__file__))
...at the top of a module.
Also, it is not rare to do further concatenations in order to declare where static files are located:
CONF_FILE = os.path.abspath(os.path.join(HERE, 'app.conf'))
CERT_FILE = os.path.abspath(os.path.join(HERE, 'cert.pem'))
THIS_FILE = os.path.abspath(os.path.join(HERE, __file__))
A quick search within Python source code shows this is indeed a very common pattern:
$ find . -name \*.py | xargs grep "os\.path" | grep __file__
Just some examples (there are *many*):
I think there's space for improvements here so my proposal is to add a simple os.path.here() function working like this:
>>> # assuming /home/giampaolo/app/run.py is the current module:
>>> os.path.here()
/home/giampaolo/app/
>>> os.path.here(__file__)
/home/giampaolo/app/run.py
>>> os.path.here('..')
/home/giampaolo/
The implementation is pretty straightforward:
def here(concat=None):
"""Return the absolute path of the parent directory where the
script is defined.
"""
here = os.path.abspath(os.path.dirname(__file__))
if concat is not None:
here = os.path.abspath(os.path.join(here, concat))
return here
Thoughts?
--