Bitpath

Lesson 1 · Unit 04

Imports

What import runs, what it caches, and how cycles break

13 exercisesabout 3 min

What you practise

  • What import runs 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?

Python
# 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?

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.

Python
import sys
import json

print("json" in sys.modules)       # True
print(sys.modules["json"] is json) # True
import json           # found: no work

Concept

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.

Python
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.

One email when Bitpath is ready to try. Nothing else. Privacy