▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Modules and import
Split your code into files and reuse it.
🎬 Video version coming soon — read it now
A module is simply a Python file you can reuse in other programs. Splitting code into modules keeps big projects organised, and it's how you use the huge collection of code others have written.
Importing built-in modules
Three styles:
import math: use it asmath.sqrt. Clear about where things come from.from random import choice: usechoicedirectly.import datetime as dt: a shorter nickname. You'll seeimport pandas as pdeverywhere.
Avoid from module import *. It pulls in every name and makes code hard to follow.
Making your own module
Create a file called vizag_utils.py:
Then, in another file in the same folder:
In Colab you can create the file with the %%writefile vizag_utils.py magic at the top of a cell.
if __name__ == "__main__"
This block runs only when you run the file directly, not when another file imports it. It lets a module have its own demo or tests without them running on every import. You'll see it in almost every Python project.
Packages
A package is a folder of modules. import os.path means "the path module inside the os package".
random.py or csv.py. Python will import your file instead of the real one, and you'll get very confusing errors.In one line
A module is a reusable .py file; import it to use its code, and guard demo code with if __name__ == "__main__".
Share with a friend