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

Serhiy Storchaka storchaka at gmail.com
Mon May 7 09:14:43 EDT 2018


06.05.18 09:53, Yuval Greenfield пише:
> 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.
> 
> https://github.com/tensorflow/models/search?l=Python&q=dirname&type=
> https://github.com/django/django/search?l=Python&q=dirname&type=
> https://github.com/nose-devs/nose/search?l=Python&q=dirname&type=
> 
> 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 
> candidates.

* Additional burden on maintainers of import machinery. It is already 
too complex, and __file__ is set in multiple places. Don't forgot about 
third-party implementations.

See also issue33277: "Deprecate __loader__, __package__, __file__, and 
__cached__ on modules" (https://bugs.python.org/issue33277).

* More complex user code, because you have to handle different cases:

   - __file__ is set, but __dir__ is not set.
   - __file__ and __dir__ are set, but are not consistent.

> Reasons to add it:

Are you aware of importlib.resources?

https://docs.python.org/3.7/whatsnew/3.7.html#importlib-resources



More information about the Python-ideas mailing list