Appendix C: Organizing Python Code
You can organize the code as multiple files. Python considers each file as a module. To use a function/class in one file from another, you need to import it first.
Consider the following two files residing in the same directory.
[project_root]/student.py:
def describe(name):
print(name, 'is a student')
[project_root]/course.py:
import student
student.describe('Adam')
Notice how the course.py imports the student module and uses the student.describe function defined in the student.py file.
You can organize files into sub-directories too.
Consider the following two files.
[project_root]/utils/print_utils/misc.py:
def print_as_list(text):
print(list(text))
[project_root]/course.py:
from utils.print_utils import misc
misc.print_as_list('Adam')
Notice how the import statement uses a slightly different syntax and uses . to indicate directory nesting (i.e., utils/print_utils → utils.print_utils). In fact, there are other variations of the import syntax.
When you import a module, Python will interpret and execute any code in it.
Consider this student module being imported into the course module.
[project_root]/student.py:
def describe(name):
print(name, 'is a student')
describe('Betty')
| → | |
Notice how the output contains Betty is a student. That is because the line describe('Betty') in student.py is being executed as the student module is being imported.
To prevent execution of statements in an imported module, nest such statements under a if __name__ == "__main__": block.
In the code below, the student module can be executed to get the following output.
| → | |
When the student module is imported to another module, describe('Betty') line is no longer executed.
| → | |