Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Modules and Packages in Python

Modules and Packages in Python

A module in Python is a file with a .py extension that contains Python definitions, such as functions, classes, and variables, which can be reused in other Python programs.

  • Modules promote code reuse, better organization, and modularity. Instead of writing code again, you can import and use existing code.

Example of Creating a Module: Create a file named mymodule.py:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

Use this module in another Python file:

# main.py
import mymodule

print(mymodule.greet("Alice"))
  • Built-in Modules: Already available in Python (e.g., math, os, sys)
  • User-defined Modules: Created by users (like mymodule.py)

A package is a collection of related Python modules organized in directories containing a special init.py file, which marks the directory as a Python package.

  • Packages help in organizing large projects by grouping related modules under a common namespace. They make code easier to maintain and navigate.

Structure Example:

mypackage/
    __init__.py
    module1.py
    module2.py

Using a Package:
Assuming module1.py has a function hello():

# module1.py
def hello():
    return "Hello from module1"

You can import it like this:

from mypackage import module1

print(module1.hello())
  • Code Reusability: Avoid rewriting the same code in multiple files.
  • Organization: Break code into logical components.
  • Maintainability: Easier to maintain and debug small modules than one large file.
  • Namespace Management: Prevents naming conflicts by using module and package namespaces.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *