1 min read

Python Modules and Packages

Modules and packages are the core mechanisms for organizing code in Python. They allow you to break down large programs into small, manageable, and reusable files.

Modules

A module is simply a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

Creating a Module

Save this code in a file named mymodule.py:

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

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Using a Module

import mymodule

mymodule.greeting("Jonathan")

Packages

A package is a way of organizing related modules into a directory hierarchy.

To create a package, you create a directory with the package name and a file named __init__.py inside it. The __init__.py file can be empty.

my_package/
  __init__.py
  module1.py
  module2.py