Lesson 5 of 5 · 6 min · Organising code

Modules, packages and virtual environments

Covers: Python 3.14. Updated 13 Nov 2026. Part of the Data Analyst roadmap.

What you will learn

  • Import modules from the standard library and from your own files
  • What a package is and how imports find it
  • Install third-party packages with pip
  • Keep each project's packages separate with a virtual environment
  • The if __name__ == "__main__" pattern

In simple words

A module is just a Python file full of useful code, and importing it lets you borrow that code instead of writing it again. A package is a folder of modules. Libraries like pandas are packages other people wrote. Because different projects need different versions, you give each project its own private toolbox, called a virtual environment.

Words to know

  • Module: a single .py file you can import.
  • Package: a folder of modules that you import as one unit.
  • pip: the tool that downloads and installs packages from PyPI.
  • Virtual environment: an isolated copy of Python and packages for one project.

Importing

import math
print(math.sqrt(16))        # 4.0

from datetime import date
print(date.today())

from pathlib import Path as P     # rename on import
import statistics as stats
print(stats.mean([2, 4, 6]))      # 4
  • import math keeps the name prefix (math.sqrt): clear where things come from.
  • from math import sqrt brings in one name.
  • Avoid from module import *: it dumps unknown names into your file.

The standard library is large and installed with Python: csv, json, datetime, pathlib, statistics, collections, re, sqlite3. Look there before installing anything.

Your own modules

Save this as money.py:

def with_gst(price, rate=18):
    return price * (1 + rate / 100)

In another file in the same folder:

import money
print(money.with_gst(1000))     # 1180.0

Python searches the folder of the running script first, then installed packages. Do not name your file after a standard module (random.py, csv.py): yours would be imported instead of the real one.

Packages

A folder with modules is a package. Add an __init__.py file (it may be empty) to make intent clear:

shop/
    __init__.py
    pricing.py
    reports.py
main.py
from shop.pricing import with_gst
from shop import reports

Folders without __init__.py still work as namespace packages, but explicit packages are the common choice for application code.

The main guard

A file is both a module and a script. Code at the top level runs on import too. Put the script behaviour under a guard:

def main():
    print(with_gst(1000))

if __name__ == "__main__":
    main()

When you run python money.py, __name__ is "__main__" and main() runs. When another file imports it, __name__ is "money", so nothing runs by accident.

pip and virtual environments

Packages such as pandas come from PyPI and are installed with pip. Install them into a virtual environment, not into the system Python:

python -m venv .venv                # create
source .venv/bin/activate           # Linux and macOS
.venv\Scripts\activate              # Windows
pip install pandas
pip list
pip freeze > requirements.txt       # record exact versions
pip install -r requirements.txt     # recreate the same set elsewhere
deactivate

Why: project A may need one pandas version and project B another. A virtual environment gives each its own set, so upgrades in one cannot break the other. Do not commit the .venv folder; commit requirements.txt.

Use python -m pip rather than bare pip when more than one Python is installed: it guarantees the package goes to the Python you mean.

Common mistakes

  • Installing packages globally and later getting version conflicts.
  • Naming your file pandas.py or random.py, which shadows the real module.
  • Circular imports, where two modules import each other. Move the shared code to a third module.
  • Forgetting to activate the environment, then wondering why import pandas fails.

Try it yourself

  1. Create money.py with one function and import it from a second file.
  2. Add the __main__ guard and confirm it runs from the command line but not on import.
  3. Create a virtual environment, install pandas, run pip freeze, and read the output.
  4. Use statistics.median and collections.Counter from the standard library on a small list.

Check yourself

What is the difference between a module and a package?

A module is one .py file. A package is a folder of modules, imported by its folder name.

Why use a virtual environment?

To keep each project's packages and versions separate, so installing or upgrading in one project cannot break another.

What does if __name__ == "__main__": do?

It runs the code beneath it only when the file is executed directly, not when it is imported.

How do you record and recreate a project's packages?

pip freeze > requirements.txt records them; pip install -r requirements.txt installs the same set.

Interview questions

What happens when you import a module twice?

Python runs the module's top-level code only the first time and caches it in sys.modules; later imports reuse the cached module.

How would you fix a circular import?

Move the shared pieces into a third module that both import, or import inside the function that needs it.

Where does Python look for modules?

The script's folder, then the paths in sys.path (including installed packages in the active environment and the standard library).

Summary

  • Import with import x or from x import name; prefer the standard library first.
  • Packages are folders of modules; use the __main__ guard for runnable files.
  • Use python -m venv, activate it, install with pip, record with requirements.txt.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Python essentials for analysts for Data Analyst and scores every answer, with what to fix.