- __init__() function
- *args and **kwargs
- Aliases
- and operator
- argparse
- Arrays
- asyncio
- Booleans
- Break statement
- Bytes
- Classes
- Closure
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- Data types
- Data visualization
- datetime module
- Decorator
- Dictionaries
- Dictionary comprehension
- Django
- Docstrings
- Dunder methods
- Encapsulation
- enum
- enumerate() function
- Equality operator
- Error handling
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Inheritance
- Integers
- Iterator
- JSON
- Lambda function
- len() Function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List reverse() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Modulo operator
- Multiline comment
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- Optional arguments
- or operator
- Override method
- Package manager (pip)
- Packages
- Pandas library
- Parameters
- pathlib module
- Pickle
- Polymorphism
- print() function
- Property()
- Protocol
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Script
- Set comprehension
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Type casting
- Type hints
- uuid module
- Variables
- Virtual environment
- What is Python?
- While loops
- yield
- Zip function
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.
Learn Python on Mimo
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 packageformatting.pyandmath_tools.pyare modules inside the package__init__.pymarks 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:
Python
from utilsimport formatting
print(formatting.make_title("hello from packages"))
And inside formatting.py:
Python
defmake_title(text: str) ->str:
return text.title()
Importing a specific function
If you only need one function, import just that:
Python
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:
Python
import utils.math_toolsas mt
print(mt.add(5,10))
And in math_tools.py:
Python
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 handlingmodels/for data modelsservices/for business logictests/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.pydate_helpers.pystring_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:
requestsnumpyflaskpandas
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:
Python
defsave_note(path: str, note:str) ->None:
withopen(path,"a", encoding="utf-8")as file:
file.write(note +"\n")
validation.py:
Python
defis_valid_note(note: str) ->bool:
returnlen(note.strip()) >0
app.py:
Python
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:
Python
defremove_extra_spaces(text: str) ->str:
return" ".join(text.split())
formatting.py:
Python
defshout(text: str) ->str:
return text.upper() +"!"
__init__.py:
Python
from .cleaningimport remove_extra_spaces
from .formattingimport shout
Now users can do this:
Python
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:
Python
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:
- The current folder your script runs from
- Installed packages in your environment
- Standard library packages like
jsonandpathlib
You can inspect the search path like this:
Python
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):
Python
from utils.formattingimport make_title
Relative import (useful inside a package):
Python
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.pycan break imports because it shadows the built-injsonpackage
Running scripts the wrong way
- running a module inside a package directly can break relative imports
- using
python -m package_nameusually 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.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot