05 / BUILDING USEFUL TOOLS · LESSON 18

Use a local module

Import a supplied helper and keep imports free of execution side effects.

13 min · learn at your pace

Split work into modules

A Python file is also a module. from inventory_helpers import normalise_name imports a function from the supplied inventory_helpers.py beside your script. You can inspect the helper under the supplied-files panel. No package installation is involved.

Python searches its import path and normally caches imported modules in the running interpreter. A fresh Check starts with the original files and a new worker, so it also clears that cache. Avoid naming your own file after a standard-library module such as json.py, which could shadow the module you meant to import.

Separate reusable code from starting a program

When a file is run as a script, its __name__ is "__main__". When imported, it has its module name instead. Put demonstration or command-line work under if __name__ == "__main__": so another module can import functions without triggering prints or prompts.

This lab keeps one editable entrypoint, main.py. Supplied helper files demonstrate how a multi-file project fits together. In your own editor later, you can move reusable functions into modules you maintain and test independently.

Try an example.py
from inventory_helpers import normalise_name
print(normalise_name("  WEB-01  "))
YOUR TURN

Put it into practice.

Import normalise_name from inventory_helpers. Define build_labels(names) returning a list of normalised names in the same order. A guarded demonstration may print labels, but importing your script as inventory_tool must produce no output and ask no questions.

See an explained solution
One way to solve it.py
from inventory_helpers import normalise_name
def build_labels(names):
    return [normalise_name(name) for name in names]

if __name__ == "__main__":
    print(build_labels([" WEB-01 ", "Db-02"]))

The helper owns normalisation and validation. The main guard makes the same file useful both as an importable tool and as a runnable demonstration.