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

Barry Warsaw barry at python.org
Mon May 7 22:09:20 EDT 2018


Yuval Greenfield wrote:

> I often need to reference a script's current directory. I end up writing:
> 
> import os
> SRC_DIR = os.path.dirname(__file__)

The question I have is, why do you want to reference the script's 
current directory?

If the answer is to access other files in that directory, then please 
consider using importlib.resources (for Python 3.7) and 
importlib_resources (for Python 2.7, 3.4-3.6).

__file__ simply isn't safe, and pkg_resources can be a performance 
killer.  The problem of course is that if you're writing an application 
and *any* of your dependencies use either technique, you are going to 
pay for it.  This is exactly why Brett and I wrote importlib.resources. 
We wanted a consistent API, that allows custom loaders to play along, 
and which is about as efficient as possible, uses Python's import 
machinery, and is safe for uses like zipapps.

now-you-don't-have-to-attend-my-pycon-talk-ly y'rs,
-Barry




More information about the Python-ideas mailing list