In Python, a package is a way to organize related modules into a directory structure. Instead of keeping all files in one place, packages help group similar functionality together, making code easier to manage, reuse and maintain especially in large projects.
Creating a Package
Creating a package involves just three steps:
- Create a directory (this will be package name)
- Add Python files (modules) inside it
- Add an __init__.py file to mark it as a package
Let's create a package named Cars and build three modules in it namely, Bmw, Audi and Nissan. Below is the folder structure:
cars/
│── __init__.py
│── bmw.py
│── audi.py
│── nissan.py
bmw.py: This module defines the BMW class, which contains a method to return a list of BMW car models.
class BMW:
def models(self):
return ["i8", "X1", "X5"]
audi.py: This module defines the Audi class, which provides Audi car models through a method.
class Audi:
def models(self):
return ["A3", "A6", "Q7"]
nissan.py: This module defines the Nissan class, used to return popular Nissan car models.
class Nissan:
def models(self):
return ["Altima", "Rogue", "370Z"]
init.py: The __init__.py file makes the cars directory a package. By importing classes here, it allows direct access to BMW, Audi, and Nissan classes when the package is imported.
from .bmw import BMW
from .audi import Audi
from .nissan import Nissan
This file allows direct access to classes when importing the package.
Accessing the Package
Now, create a file named main.py in the same directory where the cars package exists. This file will be used to import and access the classes defined inside the package modules.
from cars import BMW, Audi, Nissan
bmw = BMW()
print(bmw.models())
audi = Audi()
print(audi.models())
nissan = Nissan()
print(nissan.models())
Output
['i8', 'X1', 'X5']
['A3', 'A6', 'Q7']
['Altima', 'Rogue', '370Z']
Explanation:
- from cars import BMW, Audi, Nissan: imports the classes directly from the package using __init__.py.
- BMW(), Audi(), and Nissan(): create objects of their respective classes.
- models(): is called on each object to retrieve the list of car models.
Different Ways to Import from a Package
Python provides multiple ways to import content from a package depending on how much access you need.
1. Import a Specific Module: used when only one class or module is required from the package
from cars.bmw import BMW
This statement imports only the BMW class from the bmw module inside the cars package.
2. Import the Whole Package: used when modules need to be accessed using the package name
import cars
This statement imports the entire cars package, and its modules or classes must be accessed using dot notation.
3. Import Everything Using *: used to import all objects defined in __init__.py
from cars import *
This statement imports all classes and objects listed in the __init__.py file.
Note: This works only if objects are explicitly defined in __init__.py and is generally not recommended for large projects.