[Python-ideas] __dir__ in which folder is this py file

Yuval Greenfield ubershmekel at gmail.com
Sun May 6 02:53:11 EDT 2018

Hi Ideas,

I often need to reference a script's current directory. I end up writing:

import os
SRC_DIR = os.path.dirname(__file__)

But I would prefer to have a new dunder for that. I propose: "__dir__".  I
was wondering if others would find it convenient to include such a shortcut.

Here are some examples of dirname(__file__) in prominent projects.


Reasons not to add __dir__:
* There already is one way to do it and it's clear and fairly short.
* Avoid the bikeshed discussion of __dir__, __folder__, and other

Reasons to add it:
* os.path.dirname(__file__) returns the empty string when you're in the
same directory as the script. Luckily, os.path.join understands an empty
string as a ".", but this still is suboptimal for logging where it might be
surprising to find the empty string. __dir__ could be implemented to
contain a "." in that case.
* I would save about 20 characters and a line from 50% of my python scripts.
* This is such a common construct that everyone giving it their own name
seems suboptimal for communicating. Common names include: here, path,
dirname, module_dir.


Yuval Greenfield

P.s. nodejs has it -
https://nodejs.org/docs/latest/api/modules.html#modules_dirname also I
apologize if this has been suggested before - my googling didn't find a
previous thread.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180506/e1b29f8f/attachment.html>

More information about the Python-ideas mailing list