In Python, modules and packages help organize code into manageable, reusable components. Modules contain functions, classes, and variables, while packages group related modules for better code organization.
Modules and Packages in Python
1. What is a Module?
A module is simply a Python file (.py) that contains definitions for functions, variables, and classes. Modules make it easy to reuse code across different parts of a project or between projects.
Creating and Using a Module
# In a file named my_module.py
def greet(name):
return "Hello, " + name
To use this module in another file, use the import
statement:
# In another Python file
import my_module
print(my_module.greet("Alice"))
Modules Quiz
What is the file extension for Python modules?
How do you access a function from an imported module?
2. What is a Package?
A package is a directory containing a collection of modules. Packages allow for a hierarchical organization of modules, which is especially useful for larger applications. Packages are identified by an __init__.py
file in their directory.
Creating a Package
To create a package named my_package
with a module my_module.py
:
my_package/
├── __init__.py
└── my_module.py
The __init__.py
file makes my_package
a package and can be empty or contain initialization code for the package.
Using a Package
To use a module from a package, use dot notation:
# In another Python file
from my_package import my_module
print(my_module.greet("Alice"))
Packages Quiz
What file identifies a directory as a Python package?
How do you import a module from a package?
3. Importing Modules and Packages
Python offers multiple ways to import modules:
import module_name
: Imports the module, accessed withmodule_name.function()
.from module_name import function_name
: Imports specific functions or classes directly.from module_name import *
: Imports all functions/classes from the module (not recommended due to potential conflicts).
Example
# Importing a specific function
from my_module import greet
print(greet("Alice"))
Importing Quiz
Which import statement is generally discouraged?
What's the difference between import module
and from module import func
?
4. Best Practices for Using Modules and Packages
- Use Descriptive Names: Choose module and package names that clearly indicate their functionality.
- Keep Modules Small: Divide functionality across multiple modules for easier maintenance.
- Organize Imports: Use the import convention
import statements first, then from imports
. - Limit Star Imports: Avoid
from module_name import *
as it may create conflicts and make debugging harder.
Best Practices Quiz
Why should you avoid from module import *
?
What's a good practice for module size?