Python course / Working Python
Modules and imports
Split a program across files and packages, and know what import actually does. Two modules that need each other fail on import, and knowing why is the difference between a fix and a guess.
- import forms
- __name__
- packages
- relative imports
- circular imports
- pip
- virtual environments
- what goes where
Runs in your browser. Start straight away; create an account when you want your progress kept.
import json
import sys
print("name of this module:", __name__)
print("json came from:", json.__name__)
print("already imported:", "json" in sys.modules)
if __name__ == "__main__":
print("this file was run, not imported")
name of this module: __main__ json came from: json already imported: True this file was run, not imported
What you will learn
- Move code into a second file and use it from the first.
- Choose how a name from another module arrives in yours.
- Write a file that does its work when it is run and stays quiet when it is imported.
- Group related modules into a folder and import them by a dotted name.
- Find the module that already does it before writing it yourself.
- Split a program into modules along the lines that change together.
The lessons in this module
- What a module is
- Three ways to import
- What import actually does
- Running once
- Run, or imported
- Where Python looks
- Packages
- Relative and absolute imports
- Circular imports
- The standard library
- Packages from outside: pip
- Virtual environments
- What to put where
- Work done on import
- From one file to a package
- Module review: the order desk
Ready when you are
Previous: Classes and objects. Next: Comprehensions. All modules are on the course page.