Command Palette

Search for a command to run...

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

Shadowing the standard library

The example writes its own statistics.py before the real one is ever imported, so Python finds the local file first. That is exactly what happens when you save a practice file with a standard module's name. (try/except AttributeError means: try the call, and if the name is missing, print the error instead of crashing. Topic 7.1 teaches it.)

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?

Shadowing the standard library
Sign in to run this example in your browser.

Expected output

statistics loaded yet: False
file used: statistics.py
mean: not the real mean
AttributeError: module 'statistics' has no attribute 'median'