Modules and Packages in Python

Python : Modules and Packages

A module is a file containing Python definitions and statements. A package is a collection of related modules. Modules and packages are used to organize Python code into logical groups, making it easier to work with and maintain.

In this tutorial, we will cover the basics of modules and packages in Python.

Creating a Module in Python

To create a module, you simply create a new Python file with a .py extension.

For example, let's create a module called mymodule.py:

# mymodule.py

def greeting(name):
  print("Hello, " + name)

Using a Module in Python

To use a module, you simply import it into your code using the import statement.

For example, let's use the mymodule.py module:

# main.py

import mymodule
mymodule.greeting("John")

# Output:
Hello, John

Creating a Package in Python

To create a package, you simply create a new directory and add an init.py file. The init.py file can be empty or it can contain initialization code for the package.

For example, let's create a package called mypackage:

mypackage/
  __init__.py
  mymodule.py

Using a Package in Python

To use a package, you can import its modules using the dot notation.

For example, let's use the mypackage module:

# main.py

import mypackage.mymodule
mypackage.mymodule.greeting("John")

# Output:
# Hello, John

Importing from a Package in Python

You can also import specific functions or variables from a module using the from...import statement.

// let's import the greeting function from the mymodule.py module:
# main.py

from mypackage.mymodule import greeting
greeting("John")

# Output: Hello, John

Creating a Subpackage in Python

You can create subpackages inside a package by creating subdirectories and adding init.py files.

let's create a subpackage called mysubpackage:

mypackage/
  __init__.py
  mymodule.py
  mysubpackage/
    __init__.py
    mysubmodule.py

Using a Subpackage in Python

To use a subpackage, you can import its modules using the dot notation.

# main.py

import mypackage.mysubpackage.mysubmodule
mypackage.mysubpackage.mysubmodule.mysubfunction("John")

# Output: Hello, John

Modules and packages are an important part of Python programming. They allow you to organize your code into logical groups, making it easier to work with and maintain.