Imports - parent directory

Imports in Python typically assume a flow-down design. That is the program that is making any imports is either at the same level or a higher level relative to any file it wishes to import. However this isn't always the case.

To do so, we will need to use the sys library. This is a powerful library that can directly alter the computer's file system, so use it with care. We desire one specific function in it, the one that tells the system where to look when making imports. Let's look at this file structure so that we can successfully import helperA and helperB into main.py.

This will work if we call it at the same level as main.py, however if we try and call it from any other directory, it will fail. This is because use of the double periods (..), this tells the interpreter to look relative from where it's being called, and once this changes, it becomes lost.

Before moving on, the notation .. is standard notation to indicate a directory parent to the current location. The notation with a single period, (.) indicates the current directory. If we want to look two levels above, then use ../../, and so on.

So how can we import this such that it will still work regardless of where the file is being called from? We can do two things. We can add the directory that is minimally parent to every file that needs to be imported (so avoid adding root please), and then import relative from there.

This allows us to call our code when located in the lesson_01 directory, or even higher. Having to know the absolute path to the top directory required for importing isn't always available. For example sharing code with another, the location of their code will likely have a different absolute path than someone else. In this case, it can work to add a constant directory and then call the code from this one location. This prevents flexibility in where the file can be run from, but still provides access to all the required files while providing consistency. To do so, one such way is to use the current working directory; this can be found with the os library and the function os.getcwd() within it. To run the code one needs to move to the minimally root directory, make sure imports are relative to it, and only call it from there.

Practice Question

Assume the following directory structure.

Q01.a. Which location should be used to enable the files helperA and helperB to be imported?

Q01.b. And for helperA and helperC to be imported?

score: 0%