[Python-ideas] __dir__ in which folder is this py file
steve at pearwood.info
Sun May 6 06:23:47 EDT 2018
On Sun, May 06, 2018 at 06:53:11AM +0000, Yuval Greenfield 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__)
> 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.
Not really, no. If I'm doing file name processing such that I need the
script's directory, I already need to import os, so providing this
pre-calculated would only save at most a single line. Not every
one-liner needs to be a built-in.
I don't strongly oppose this, but given how easy it is, I don't really
see the point. New features add a cost, and while these costs are
- one more thing to document
- one more thing for people to learn and memorise
- every script pays the cost of calculating this dirname
whether it is needed or not
etc, the corresponding benefit is also tiny, so it is not clear to me
that the benefit from having this is greater than the cost of having it.
If you can demonstrate a clear, significant benefit, the balance would
shift in favour of this proposal, but as it stands, it seems like a mere
matter of personal taste. So in the absence of any clear, non-trivial
benefit, I'm vaguely -0 on this.
However, I am opposed to the use of __dir__ as the dunder name, since
__dir__ is already used as the dunder method for the dir() builtin. Even
though strictly speaking there is no conflict between a method and a
module global, conceptually they would be better kept distinct.
If this is approved, I suggest __dirname__ instead.
> Reasons not to add __dir__:
> * There already is one way to do it and it's clear and fairly short.
> 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.
Can you give an example where the empty string actually is a real
problem, rather than just "might be"?
Bonus points if it was an actual problem in real code, not just a
hypothetical problem made up as an example.
For what it's worth, if there is such a genuine problem, that would
shift me to +0.5 on the proposal:
SRC_DIR = os.path.dirname(__file__) or '.'
More information about the Python-ideas