Skip to main content

Command Palette

Search for a command to run...

Python Basics — Day 19 Modules & Packages (import, from, __main__)

Published
3 min read
S

Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey

Building skills in Python and full-stack development, with a focus on web apps and system design

Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering

From Python basics to full-stack projects, sharing my progress as I grow into a developer

Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development

Starting from this post , I’ve changed the format form explaining concepts to presenting problems and solving them. Personally, I’ve found that I learn best when I face a problem and work through the process of fixing it.

Learning Goal

Learn how to split a Python project into multiple files using modules and packages,
and understand how import, from, and __main__ work in a real-world context.


01. Problem Scenario

Your calculator script is getting too messy.
All your functions are in one file, making it hard to maintain.
Let’s refactor the project by separating logic into modules, organizing them into packages,
and controlling code execution using __main__.


02. Step 1 – Creating a Module

In Python, a single .py file is a module.
We’ll create a new file calc.py to store the calculator’s logic.

calc.py

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

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b

main.py

import calc

print("3 + 5 =", calc.add(3, 5))
print("10 - 7 =", calc.sub(10, 7))

Now main.py only handles program execution,
while calc.py manages the logic, making the code cleaner and easier to reuse.


03. Step 2 – Different Ways to Import

# Import the entire module
import math
print(math.sqrt(16))

# Import specific functions
from math import sqrt, pi
print(sqrt(25), pi)

# Use an alias
import math as m
print(m.pow(2, 3))

Using from and as can make your code shorter and more readable.


04. Step 3 – Building a Package

As your project grows, you can organize related modules inside a folder, called a package.

my_package/
    __init__.py
    math_ops.py
    string_ops.py
main.py

math_ops.py

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

main.py

from my_package import math_ops

print(math_ops.add(2, 3))   # 5

The presence of __init__.py tells Python that this folder should be treated as a package.


05. Step 4 – Understanding __name__ and __main__

Python can tell whether a file is being executed directly or imported as a module.
You can control behavior with this structure:

# test.py
def hello():
    print("Hello!")

if __name__ == "__main__":
    hello()

Explanation:

  • When a file runs directly: __name__ == "__main__"

  • When imported: __name__ == "test"

$ python test.py      # Output: Hello!
>>> import test       # No output

This prevents test code from running automatically when a module is imported.


06. Step 5 – Installing External Libraries

You can install third-party modules from the Python Package Index (PyPI) using pip.

pip install requests
import requests

res = requests.get("https://api.github.com")
print(res.status_code)

The requests library is commonly used for handling HTTP requests and APIs.


07. Step 6 – Extended Practice Ideas

  1. Add new functions to calc.py

    • power(a, b) → exponentiation

    • sqrt(n) → square root

  2. Import only what you need in main.py

     from calc import add, sub
    
  3. Add a startup message in main.py

     if __name__ == "__main__":
         print("Calculator App Starting...")
    

This message should appear only when the script runs directly,
not when imported from another file.


Key Takeaways

ConceptDescription
ModuleA single .py file used to organize related code
PackageA folder containing multiple modules (__init__.py required)
import / fromUsed to include modules and their functions
name / mainDistinguishes direct execution from import
pip installInstalls external Python libraries

Python Basics

Part 19 of 21

A collection of study notes from my university and self-learning journey. This series covers Python fundamentals step by step — from setup to core concepts — to help both myself and others build a solid foundation in coding.

Up next

Python Basics — Day 20 Python Standard Library

Day 20 – Python Standard Library Project: Build a “Lotto Generator & Date Calculator” Learning Goal Learn how to use Python’s built-in standard libraries—math, random, datetime, time, and os—by solving real problems in one mini project:a lotto numbe...

More from this blog

S

Sabin’s DevLog

21 posts

I plan to upload everything I study and prepare here. I hope it can be helpful to others, and I also want my future self to see the learning journey I’ve been through.