DSPython Logo DSPython

Modules & Packages

Learn how to import and use Python's powerful code libraries.

Python ADV Intermediate 30 min

🧰 Introduction: The "Toolbox" Analogy

Imagine you are building a house. You don't forge your own hammer, saw, or drill from raw metal every time you need them. Instead, you open your Toolbox and pick the tool you need.

In Python:
1. A Module is like a specific tool (e.g., a Calculator, a Calendar).
2. The Standard Library is the Toolbox that comes free with Python.
3. Importing is the act of taking the tool out of the box to use it.

This follows the DRY (Don't Repeat Yourself) principle. Why write code to calculate the square root of a number when Python already has a pre-written, error-free tool (`math`) to do it for you?

📦 Topic 1: Built-in Modules

Python is famous for being "Batteries Included". This means it comes installed with hundreds of useful modules. A module is simply a Python file (.py) containing functions and variables.

📝 The Syntax:

To use a module, you must tell Python to load it using the import keyword.

💻 Example: Using the 'math' Module

# 1. Import the module
import
math
# 2. Use functions using 'dot' notation (module.function)
root = math.sqrt(16)
pi_val = math.pi

print(f"Square root of 16 is {root}")
print(f"Value of PI is {pi_val}")

# Output:
# Square root of 16 is 4.0
# Value of PI is 3.141592653589793

💡 Common Built-in Modules:

  • math: Mathematical functions.
  • random: Generating random numbers.
  • datetime: Working with dates and time.
  • os: Interacting with the Operating System (files/folders).
  • json: Working with JSON data.

🔄 Topic 2: Ways to Import

Python offers flexibility in how you import modules. You can import the whole thing, just one specific tool, or even rename the module.

1. Renaming (Aliasing)

If a module name is too long, give it a nickname using as.

import math as m
print(m.pi)  # Much shorter!

2. Importing Specific Items

If you only need the hammer, don't bring the whole toolbox. Use from ... import ....

from math import sqrt, pi

# Now you don't need 'math.' prefix
print(sqrt(25))

⚠️ Warning: The Star (*) Import

You might see from math import *. This imports EVERYTHING. Avoid this! It dumps hundreds of names into your code, which can cause conflicts if you have variables with the same names.

🛠️ Topic 3: Creating Custom Modules

A module is not magic. It is just a Python file! You can create your own modules to organize your code.

💻 Step 1: Create 'my_tools.py'

# Save this code in a file named my_tools.py
def
greet(name):
return f"Hello, {name}!"

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

💻 Step 2: Use it in 'main.py'

# Now import your custom module
import
my_tools
# Use the functions you wrote!
message
= my_tools.greet("Vinay")
print(message)  # Output: Hello, Vinay!
total
= my_tools.add(5, 10)
print(total)    # Output: 15

🌍 Topic 4: Packages & PIP

A Package is a collection of modules organized in folders. It's like a "Mega-Toolbox".

🛒 PyPI and PIP:

Sometimes the standard library isn't enough. Python has a huge repository called PyPI (Python Package Index) where developers share their packages (like pandas, numpy, requests).

To install these external packages, we use a tool called PIP in the terminal (command prompt).

# Terminal Command (Not Python Code)
pip install pandas

📚 Module Summary

  • Module: A single .py file with code.
  • Package: A folder containing multiple modules and an __init__.py file.
  • Import: Brings code from a module into your file.
  • Standard Library: Built-in modules (math, random, os).
  • PIP: Tool to install external packages from the internet.

🤔 Interview Q&A

Tap on the questions below to reveal the answers.

A Module is a single file (e.g., math.py) containing Python code. A Package is a directory (folder) containing multiple modules and a special file called __init__.py that tells Python this directory is a package.

It imports every single function and variable from the module into your current namespace. This can lead to Naming Conflicts (e.g., if both modules have a function named calculate(), one will overwrite the other). It also makes it hard to tell where a function came from.

It is a special file that executes when a package is imported. Its main purpose is to tell Python that the directory should be treated as a package. In newer versions of Python (3.3+), it is optional but still recommended for initialization code.

Python looks in a list of directories defined in sys.path. This includes:
1. The current directory.
2. The PYTHONPATH environment variable.
3. The installation-dependent default path (where Standard Library lives).