Title: Provide convenience function for paths relative to the current module
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.6
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: madison.may, martin.panter, r.david.murray
Priority: normal Keywords:

Created on 2015-06-06 16:47 by madison.may, last changed 2015-06-07 01:49 by r.david.murray.

Messages (4)
msg244920 - (view) Author: Madison May (madison.may) * Date: 2015-06-06 16:47
I often find myself trying to access a file relative to the module I'm working on.  When this occurs, I'll often use something like the following:

os.path.abspath(os.path.join(os.path.dirname(__file__), "data/resource.pkl"))

I have good reason to believe that I'm not the only one, as searching for other examples of this code on github returns ~20k exact matches:

Low priority, but a more concise way of achieving the same result would be much appreciated.
msg244933 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2015-06-06 23:49
This feature could be handy for finding test files in test suites.  However I don’t think the abspath() step is necessary. We kind of want a urljoin() for OS paths, that automatically removes the current file name. As a new feature I think it would be too late for 3.5.

There is the recently added “pathlib” module. I haven’t used it much, and it doesn’t have the perfect API for the job, but maybe this is good enough:

vadmium@localhost:~/proj/python/lib$ cat demo_package/
from pathlib import PurePath
vadmium@localhost:~/proj/python/lib$ python3 -bWall -c 'import demo_package'
msg244934 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2015-06-06 23:56
There is also pkgutil.get_data(), but that returns the file contents rather than file path, which has rarely been useful to me.
msg244938 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2015-06-07 01:49
The pkguitil.get_data function is the *right* way to access package-relative data (because in the general case the data may not be on the file system), and IMO it would not be a good idea to make it easier to do things the "wrong" way.  Any deficiencies with get_data (and its visibility) will, I think, be addressed as part of the ongoing effort to make using zipped applications more convenient.

So I'm -1 on adding a convenience function for this.
Date User Action Args
2015-06-07 01:49:24r.david.murraysetnosy: + r.david.murray
messages: + msg244938
2015-06-06 23:56:58martin.pantersetmessages: + msg244934
2015-06-06 23:49:34martin.pantersetnosy: + martin.panter

messages: + msg244933
versions: - Python 3.5
2015-06-06 16:47:47madison.maycreate