PYTHON

Python Packages: Syntax, Usage, and Examples

Python packages help you organize related modules into a folder structure so your code stays clean and easy to reuse. They also make it possible to install and share code using tools like pip.


How to Use Packages in Python

A package is basically a directory that contains Python files (modules). You can import code from a package the same way you import built-in modules.

Basic package structure

Here’s what a small package might look like:

my_app/
    main.py
    utils/
        __init__.py
        formatting.py
        math_tools.py

  • utils/ is the package
  • formatting.py and math_tools.py are modules inside the package
  • __init__.py marks the folder as a package in older Python versions, and it still has real uses today

Importing a module from a package

Inside main.py, you can import like this:

from utilsimport formatting

print(formatting.make_title("hello from packages"))

And inside formatting.py:

defmake_title(text: str) ->str:
return text.title()

Importing a specific function

If you only need one function, import just that:

from utils.formattingimport make_title

print(make_title("python packages are neat"))

This keeps your code short and makes it obvious what you’re using.

Using an alias for long imports

Some imports get annoying to type, so aliases help:

import utils.math_toolsas mt

print(mt.add(5,10))

And in math_tools.py:

defadd(a: int, b:int) ->int:
return a + b

Running a package like a script

Packages can also include an entry point file named __main__.py, which lets you run them directly.

Structure:

weather_tool/
    __main__.py
    api.py

Then you can run:

python -m weather_tool

This is a common pattern for CLI tools.


When to Use Packages

Packages are helpful anytime your code starts spreading across files, or when you want to reuse code in multiple projects.

1) Organizing medium or large projects

A single file works until it doesn’t. Once your project grows, splitting logic into folders becomes a relief.

Example setup:

  • routes/ for request handling
  • models/ for data models
  • services/ for business logic
  • tests/ for automated tests

Packages make those folders importable, so everything stays connected.

2) Sharing code inside a team

A package is a clean way to share utilities across multiple scripts.

Instead of copy-pasting the same helper functions into five files, you keep them in one place:

  • logging_helpers.py
  • date_helpers.py
  • string_helpers.py

Then your teammates import them like normal Python code.

3) Building reusable libraries for multiple projects

A lot of developers end up with personal “toolbox” packages.

Example:

  • one package for working with CSV and Excel files
  • one package for API calls and retry logic
  • one package for cleaning data

Packages turn those into reusable building blocks instead of project-specific hacks.

4) Installing and using third-party tools

Every time you install something with pip, you’re installing a package.

Examples:

  • requests
  • numpy
  • flask
  • pandas

Knowing how packages work helps you understand where those libraries live, and how imports actually find them.


Examples of Packages in Python

Let’s go through some realistic examples you’d see in everyday work.

Example 1: A “helpers” package for a personal project

Folder structure:

note_app/
    app.py
    helpers/
        __init__.py
        storage.py
        validation.py

storage.py:

defsave_note(path: str, note:str) ->None:
withopen(path,"a", encoding="utf-8")as file:
        file.write(note +"\n")

validation.py:

defis_valid_note(note: str) ->bool:
returnlen(note.strip()) >0

app.py:

from helpers.storageimport save_note
from helpers.validationimport is_valid_note

note =input("Write a note: ")

if is_valid_note(note):
    save_note("notes.txt", note)
print("Saved!")
else:
print("Note was empty, try again.")

This is small, but already much easier to maintain than one giant file.


Example 2: Using __init__.py to expose a clean API

Sometimes you want users to import directly from the package, not from the deeper file.

Structure:

text_tools/
    __init__.py
    cleaning.py
    formatting.py

cleaning.py:

defremove_extra_spaces(text: str) ->str:
return" ".join(text.split())

formatting.py:

defshout(text: str) ->str:
return text.upper() +"!"

__init__.py:

from .cleaningimport remove_extra_spaces
from .formattingimport shout

Now users can do this:

from text_toolsimport remove_extra_spaces, shout

print(shout(remove_extra_spaces("hello     world")))

That feels clean and “library-like.”


Example 3: Installing packages with pip

Third-party packages are installed into your environment, then imported in your code.

pip install requests

Then:

import requests

response = requests.get("https://example.com")
print(response.status_code)

If this import fails, it usually means one of these things happened:

  • you installed the package in a different environment
  • you’re using the wrong Python interpreter
  • your virtual environment is not activated

Example 4: Using packages in a virtual environment

Virtual environments keep package installs isolated per project, so dependencies don’t clash.

Create and activate:

python -m venv .venv

Activate on macOS/Linux:

source .venv/bin/activate

Activate on Windows:

.venv\Scripts\activate

Then install packages:

pip install flask

Now Flask is available only inside that environment.

This is one of the best habits you can build early.


Learn More About Packages

Packages have a few rules and details that are easy to miss, especially when you start building real projects.

Packages vs modules

People mix these up all the time, so here’s the simple version:

  • Module: a single Python file, like math_tools.py
  • Package: a folder that contains modules, like utils/

So utils.math_tools means: package utils, module math_tools.


How Python finds packages

Python looks for imports in a few places, in this rough order:

  1. The current folder your script runs from
  2. Installed packages in your environment
  3. Standard library packages like json and pathlib

You can inspect the search path like this:

import sys
print(sys.path)

If your code can’t find a package you created, the package folder is often in the wrong place, or the script is being run from a different directory than you expect.


Absolute imports vs relative imports

Inside packages, you can import using either style.

Absolute import (clear, works well for bigger projects):

from utils.formattingimport make_title

Relative import (useful inside a package):

from .formattingimport make_title

That dot means “from the current package.”

Relative imports are common inside libraries, but they can behave differently if you try to run the module file directly. Running the package with python -m ... avoids many headaches.


Namespace packages

Python can also create packages without an __init__.py file in some setups. These are called namespace packages.

You’ll run into them in larger ecosystems, especially when multiple packages share the same top-level name.

For beginners, the key takeaway is simple: adding __init__.py keeps things predictable.


The site-packages folder

When you install third-party packages, they usually go into a folder named site-packages.

That folder is part of your environment, and Python scans it when you import external libraries.

If you ever wondered “where did requests go?”, that’s one answer.


Packaging for distribution

If you want to publish your own package so others can install it with pip, you’ll typically create:

  • a pyproject.toml
  • a version number
  • metadata like author name and license
  • build configuration

A lot of devs don’t need this at first, but it becomes useful if you build internal tools or open-source libraries.


Common beginner mistakes with packages

Putting files in the wrong folder

  • utils/ needs to be inside the project, not next to it

Naming conflicts

  • naming your file json.py can break imports because it shadows the built-in json package

Running scripts the wrong way

  • running a module inside a package directly can break relative imports
  • using python -m package_name usually works better

Forgetting the environment

  • installing packages globally, then running code inside a virtual environment without them installed

Summary

Packages are how Python organizes code into folders you can import from. You use them to keep projects tidy, share helper code, and install third-party libraries through pip. Once your scripts grow past a couple of files, packages stop being “extra structure” and start feeling like common sense.