Skip to content
IT Vizag
← Files, Modules & Packages

▶ 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

Lesson 4 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

Three styles:

  • import math: use it as math.sqrt. Clear about where things come from.
  • from random import choice: use choice directly.
  • import datetime as dt: a shorter nickname. You'll see import pandas as pd everywhere.

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:

🔒 Code example: sign up free (above) to unlock it.

Then, in another file in the same folder:

🔒 Code example: sign up free (above) to unlock it.

In Colab you can create the file with the %%writefile vizag_utils.py magic at the top of a cell.

if __name__ == "__main__"

🔒 Code example: sign up free (above) to unlock it.

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".

Tip: Never name your own file after a module you use, like 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__".

Saved on this device. Sign in to keep progress everywhere.

Share with a friend