Lesson 1 · Unit 04
Imports
What import runs, what it caches, and how cycles break
What you practise
- What
importruns and caches,__name__ == "__main__", packages, a circular import untangled
Try a question from this lesson
Pick one
A module with a print at the top level is imported three times. How many times does "loading config" appear in the output?
# write(name, text) saves a module file
write("config.py", """
print("loading config")
PORT = 80
""")
import config
import config
from config import PORT
print(PORT)Hint
What would it cost if every import in a large program ran the file again?
Correct answer
1
Why
The first import runs the file and stores the module. The other two find it already loaded and only bind names. Top-level code in a module runs once per program, however many files import it.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Modules are cached
The first import of a module runs its file, top to bottom, and keeps the resulting module object in the dict sys.modules.
Every later import of that name, anywhere in the program, finds it there and just binds a name. One module object, one set of globals, shared by all who import it.
import sys
import json
print("json" in sys.modules) # True
print(sys.modules["json"] is json) # True
import json # found: no workConcept
The name of a module
Every module has a global called __name__. In an imported module it is the module's name. In the file you actually ran, it is the string "__main__".
That is all if __name__ == "__main__": means: run this part when the file is the program, skip it when the file is imported.
import json
print(json.__name__) # json
print(__name__) # __main__10 more exercises in the app
- 1× order the lines
- 3× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.