CodingNic

Modules, Packages, and Virtual Environments

Packages

Modules, Packages, and Virtual Environments 28 min read

Packages

Packages

As projects grow, even modules may not be enough.

You may need to group related modules together.

Python uses packages for this.

What Is a Package?

A package is a folder that contains Python modules.

It helps organize larger projects.

Simple Example

Project structure:

text
store/
    products.py
    orders.py
    users.py

The store folder acts like a package.

Why Packages Matter

Packages help you:

  • organize many modules
  • group related code
  • keep projects clean
  • build larger apps

Import from a Package

If you have:

text
store/products.py

And inside:

python
def show_products():
    print("Products list")

Use it in main.py:

python
from store import products

products.show_products()

Output

text
Products list

Import Specific Function

python
from store.products import show_products

show_products()

Output

text
Products list

Nested Packages

Packages can contain folders too.

text
app/
    users/
        login.py
    reports/
        sales.py

Example Import

python
from app.users import login

About init.py

Older Python projects often use:

text
__init__.py

inside package folders.

It marks the folder as a package.

Modern Python can often work without it, but you may still see it.

Common Beginner Errors

Wrong Folder Name

Check spelling carefully.

Missing File in Package

Make sure the module exists.

Wrong Import Path

Use dots correctly.

Code Along

Create package:

text
school/
    students.py

Add one function and import it.

Mini Challenge

Create package:

text
tools/
    math_tools.py

Add:

python
def double(n):
    return n * 2

Import and print:

text
10

Real World Use Case

Large apps use packages for users, payments, reports, APIs, database code, and utilities.

Quiz

  1. What is a package?
  2. How is a package different from a module?
  3. Why use packages?
  4. What is __init__.py?

Assignment

Create a package with two modules and import one function from each.

Summary

You learned that packages group related modules into folders to organize larger Python projects.