Search code examples
pythonpython-module

Doing smart things with __file__ in python (what are they talking about?)


I keep seeing reference saying something like:

"people doing smart thing with __file__"

mostly in the context of the python packaging and packaging wars.

Guess I'm missing something because as far as I can tell this is just an attribute of the model specifing the file name and path, as explained in this SO question

what's so special about __file__ and what are some examples for "clever things" people are doing with it?


Solution

  • If you like to load the code you're working via import by putting its project directory under your PYTHONPATH, and the code depends on data files you've stored in the project directory, you can use __file__ to get the project location and retrieve the data.

    I like to load everything I work on via import, but my coworkers run the scripts I give them inside their project directories from the command line. So in these scripts I use a getwd function defined as follows to get the correct location of the project files, regardless of how the script is run:

    import os
    def getwd():
        return os.path.dirname(__file__) if '__file__' in globals() else os.getcwd()
    

    When I load the script via import, getwd returns the directory of the script. When my coworkers run the script from the command line inside their project directory, there is no global __file__, and getwd simply returns the current directory.