Preferred way to resolve package root in Python
Question: I am aware of the following way to determine the directory in which a module
is executing:

    
    
    os.path.dirname(os.path.abspath(__file__))
    

Now let's say I have a package with some modules that need to read a text file
located in a subdirectory. Something like this:

    
    
    |-- package
    |   |-- __init__.py
    |   |-- module1.py
    |   |-- subdirectory1
    |   |   |-- module2.py
    |   |-- subdirectory2
    |   |   |-- file.txt
    

Let's also say I don't want to use relative paths to the file. My intuition is
that it would be best to have a global variable defined somewhere in the
package root that gives the absolute path to the package (e.g. the above line
of code) and which could be imported by different modules whenever they needed
to reference a file inside the package. But where would this variable go? In
its own module? Or is it just better for each module to grab its own absolute
path, get the package root from that, then append on the location of the file?

Edit: another idea is to store this in `os.environ` and have the modules get
it from there. Maybe put the following line in the top level `__init__.py`:

    
    
    os.environ['MY_PACKAGE_ROOT'] = os.path.dirname(os.path.abspath(__file__))
    


Answer: You should use the import system. `subdirectory1` and `subdirectory2` should
be packages as well (you can make them so by adding an `__init__.py` file to
them, and then you can use use Python's normal import mechanism to reference
modules:

    
    
    import package.module1
    import package.subdirectory1.module2
    import package.subdirectory2.file
    

and so forth.

