Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.2 — Writing Your Own Modules
Python · Example 3 of 3

Putting a folder on sys.path

Before the sys.path.append, the module in tools/ is invisible. After it, the import works. This is a quick fix in scripts and a poor design in real projects (Topic 6.8 shows the better way).

Any .py file is a module you can import. The line if __name__ == "__main__": lets one file work both as a program and as a library, and sys.path is the list of folders Python searches, which is why a file named after a standard module can break your program.

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

Write a file temperature.py with a function to_fahrenheit(c) that turns degrees Celsius into Fahrenheit. Add a main guard that prints to_fahrenheit(100) only when the file is run directly. Then, from your program, import it and call to_fahrenheit(37).

02

Write a program that prints I am the main program when it is run directly, and I was imported when another file imports it. Use __name__ and an if/else.

03

Make a folder libs containing a module greeting.py with one function hello() that returns "hello". Add the folder libs to sys.path, import greeting, and print greeting.hello().

Explain it without notes

01

What does if __name__ == "__main__": do, and why do people use it?

02

How does Python decide which file to load for import foo?

03

Why can naming your file random.py break a program, and how do you diagnose it?

04

What is the difference between python calc.py and python -m calc?

Putting a folder on sys.path
Sign in to run this example in your browser.

Expected output

ModuleNotFoundError: No module named 'notes'
found me in tools/
search path ends with: tools