Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.1 — import: Using Code from Other Files
Python · Example 2 of 4

The first import runs the file, later ones do not

The example writes greeter.py first, so you can watch the import happen. Path(...).write_text(...) puts text into a file (Topic 7.6 teaches pathlib), and \n inside the text is a new line. importlib.invalidate_caches() tells Python to re-read the folder, which is needed when a file was created a moment ago. importlib.reload forces a second run.

import loads another module and gives you a name for it. Python runs the module's file once, the first time it is imported, and keeps the result in sys.modules so that every later import is instant and shares the same module object.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Import sqrt from math under the name root, then print root(144).

02

Write a program that imports json, then prints "json" in sys.modules (import sys too) and the module's name json.__name__.

03

Write a file shapes.py that sets SIDES = 4 and prints loading shapes. (Create it from your program with Path("shapes.py").write_text(...), as in the second example.) Import it twice and show that the message appears only once.

04

Import sys. Print "antigravity" in sys.modules. Then import the module colorsys (do not import antigravity) and print the same check again. Explain the two answers.

Explain it without notes

01

What exactly happens when Python executes import greeter for the first time?

02

What is sys.modules, and what does it explain?

03

What is the difference between import x and from x import name?

04

Why is from module import * discouraged?

The first import runs the file, later ones do not
Sign in to run this example in your browser.

Expected output

before import: False
greeter.py is running now
after first import: True
after more imports, still one run
True hello
greeter.py is running now
reload runs the file again