Your own modules
🌍 In real life. A good cook keeps a personal recipe notebook: the family's dal, the perfect rice. Whenever they cook, they open the notebook instead of working it out again. Your own code can be kept the same way: put the functions you reuse in one file, and open it from any program.
The idea in one sentence: any .py file is a module: put your helpers in helpers.py, and a program next to it can import helpers and use them.
Its words:
- your own module: a
.pyfile you wrote, imported by its name without.py __name__: each module's own name; the file you run is called"__main__"if __name__ == "__main__":: code that runs only when the file is run, not when it's imported
Step by step, for import helpers:
- Python looks for
helpers.pynext to your program. - It runs the whole file once, defining
greetandCOLOURS. helpers.greet("Ana")then calls the function from that file.
import helpers
print(helpers.greet("Ana"))
print(helpers.COLOURS)from helpers import greet
for name in ["Bo", "Cy"]:
print(greet(name))When Python imports a module it runs the whole file. To have test code in a module that runs only when you run that file itself, put it under if __name__ == "__main__":. A file you run has the name "__main__"; an imported file has its module name instead.
import shapes
print(shapes.area(4, 5))
print(shapes.__name__, __name__)Why split code into files? A long program in one file is hard to find your way around. Separate modules keep related things together (all the shape maths in shapes.py), let several programs share one copy, and let you test each module by running it on its own, thanks to the __main__ check.
Mistakes and edge cases.
- The file isn't next to the program.
import helpersgivesModuleNotFoundError: No module named 'helpers'. - Writing .py in the import.
import helpers.pyis wrong; writeimport helpers. - Test code without the main check. It runs every time someone imports the module, printing things they didn't ask for.
- Two modules importing each other. Keep imports one-way: a helpers module shouldn't import the program that uses it.
Quiz
Which line uses the function
greetfrom your own filehelpers.py?- from helpers import greet
- import helpers.py
- open helpers
What does this print, when you run it directly?
print(__name__)Code under
if __name__ == "__main__":in a module runs…- only when that file itself is run
- every time the module is imported
- never
Why put functions in your own module?
- To reuse them in many programs without copying
- To make them run faster
- Python only allows 10 functions per file
With helpers.py next to it, which line has a mistake?
import helpers print(greet("Ana"))
Coding tasks
mathtools.pyhasdouble(n)andtriple(n). Read a whole number, then print it doubled and tripled (on two lines), using the module.greetings.pyhashello(name). Writewelcome(names)that returns a list withhello(name)for each name.