Modules and Packages

Modules and Packages

What is a Module?

A module is a Python file containing functions, classes, and variables that you can import.

Importing Modules

# Import entire module
import math

print(math.pi) # 3.141592653589793 print(math.sqrt(16)) # 4.0

Import specific items

from math import pi, sqrt

print(pi) # 3.141592653589793 print(sqrt(16)) # 4.0

Import with alias

import math as m print(m.pi)

Standard Library Modules

datetime

import datetime

now = datetime.datetime.now() print(now) # 2024-01-15 10:30:45

random

import random

print(random.randint(1, 10)) # Random int 1-10 print(random.choice(['a', 'b', 'c'])) # Random choice print(random.shuffle([1, 2, 3])) # Shuffle list

json

import json

data = {"name": "John", "age": 30} json_str = json.dumps(data) # Dict to JSON string parsed = json.loads(json_str) # JSON string to dict

Creating Your Own Module

mymodule.py

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

def add(a, b): return a + b

Using Your Module

import mymodule

print(mymodule.greet("John")) # Hello, John! print(mymodule.add(3, 5)) # 8

Packages

A package is a directory containing multiple modules.

mypackage/
    __init__.py
    module1.py
    module2.py

__init__.py

This file makes a directory a package. It can also set up imports:

# mypackage/__init__.py
from .module1 import func1
from .module2 import func2

Using Packages

from mypackage import func1
func1()

pip - Package Manager

# Install package
pip install requests

List installed packages

pip list

Uninstall

pip uninstall requests

Summary

  • Modules: Python files with reusable code
  • Import: use other modules
  • Packages: directories of modules
  • pip: install external packages

Congratulations!

You've completed the Python basics course! Keep practicing and building projects.

Quiz - Quiz - Modules and Packages

1. What is a Python module?

2. How do you import a specific function from a module?

3. What does pip stand for?