A package is a collection of modules organized within a directory. This directory includes an __init__.py file, which indicates that the directory should be treated as a package.
Packages are a way of structuring Python’s module namespace by using “dotted module names”
Why use packages?
Packages allow for a structured organization of modules and help in building complex applications with different functionality split across various modules.
Example: Suppose you have a package named utilities with the following structure:
utilities/
├── __init__.py
├── file_ops.py
└── calculation.py
file_ops.py might contain file-related functions, while calculation.py could contain mathematical functions.
The __init__.py file can be empty or used to initialize the package.
Usage: You can import specific modules from a package like this:
from utilities import calculation
result = calculation.add(10, 5)
Or import everything from the package:
import utilities
result = utilities.calculation.add(10, 5)
Python Packages – Interview Questions
Q 1: What is a Python package?
Q 2: What file indicates a package?
Q 3: How do you import a module from a package?
Q 4: Can packages contain sub-packages?
Q 5: Are packages used to avoid naming conflicts?
Python Packages – Objective Questions (MCQs)
Q1. What is a Python package?
Q2. What is required inside a directory to make it a Python package?
Q3. Which is the correct way to import a module from a package?
Q4. What is the purpose of the __init__.py file in a package?
Q5. Packages help in: