Imports - child directory

Now is a good time to talk about what children/parent means in relation to Python. These are terms that indicate the level or depth a function or file is relative to a subject. Children are at a deeper level, or within more directories relative to the subject whereas parents are the opposite - at a higher level. Here's an example of some files and directories on a computer.

The / indicates the top level directory (directory means folder) on the system. It is commonly referred to as the root directory; root like a tree. Everything on the system is found within it. digicafe is either at depth zero or depth one depending on how you look at it. To clarify terminology, it is a child of the root directory or is nested within it. The directories courses and projects are children to digicafe, which then makes digicafe parent to these two directories.

To import files that are at a deeper level than the one importing, we can use dot notation. Essentially start relative to where the file is being called, then take the path to the desired file and replace slashes with dots. Assume our terminal is running code at the main.py level within the projects directory and that we wish to import example-code.py

We can then run the main code from it's current directory or even a parent directory and it would still be able to find the file to import. For example, either of these will work (assuming one is located at the respective directory).

Practice Question

Assume the following directory hierarchy, with main.py as the code to run. Which choice correctly imports the helper.py that is child to projects?

score: 0%