On 7 May 2018 at 03:44, Chris Angelico <rosuav@gmail.com> wrote:
On Mon, May 7, 2018 at 1:05 AM, George Fischhof <george@fischhof.hu> wrote:
On Sun, May 6, 2018, 1:54 AM Yuval Greenfield <ubershmekel@gmail.com> wrote:
Hi Ideas,
I often need to reference a script's current directory. I end up
writing:
import os SRC_DIR = os.path.dirname(__file__)
I would give +1 for __dirname__
Something to keep in mind: making this available to every module, whether it's wanted or not, means that the Python interpreter has to prepare that just in case it's wanted. That's extra work as part of setting up a module. Which, in turn, means it's extra work for EVERY import, and consequently, slower Python startup. It might only be a small slowdown, but it's also an extremely small benefit.
It also makes the name show up in dir(mod) for every module, and we're currently looking for ways to make that list *shorter*, not longer. So I have a different suggestion: perhaps it might make sense to propose promoting a key handful of path manipulation operations to the status of being builtins? Specifically, the ones I'd have in mind would be: - dirname (aka os.path.dirname) - joinpath (aka os.path.join) - abspath (aka os.path.abspath) Why those 3? Because with just those three operations you can locate other files relative to `__file__`, the current working directory [1], and arbitrary absolute paths, as well as remove path traversal notation like ".." and "." from the resulting paths (since abspath() internally calls normpath()). _launch_dir = abspath('') def open_from_launch_dir(relpath, mode='r'): return open(abspath(joinpath(_launch_dir, relpath)), mode) _script_dir = dirname(abspath(__file__)) def open_from_script_dir(relpath, mode='r'): return open(abspath(joinpath(_script_dir, relpath)), mode) You'd still need to import pathlib or os.path for more complex path manipulations, but they generally wouldn't be needed any more if all you're doing is reading and/or writing a handful of specific files. Cheers, Nick. [1] abspath can stand in for os.getcwd(), since you can spell the latter as abspath('.') or abspath(''), and we could potentially even make it so you can retrieve the cwd via just abspath() -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia