Importing
Learn how to import modules in Python using import, from, as, and understand how __name__ works.
Importing
As your programs grow, you do not want everything in one file. Python lets you split code across multiple files and reuse code that others have written. The way you bring that code into your file is with importing.
A module is simply a Python file. When you import it, you get access to everything defined inside it — functions, variables, classes.
import — the basics
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.floor(3.9)) # 3import math loads Python's built-in math module. You then access everything in it using math.something. The module name acts like a namespace — it keeps things organized and prevents name conflicts.
You can import multiple modules at once:
import math
import random
import osImport one module per line. It is more readable and the standard Python style. Avoid import math, random, os on one line even though it works.
from — import specific things
Instead of importing the whole module, you can import just what you need:
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793Now you use sqrt and pi directly — no math. prefix needed.
as — give it a nickname
You can rename a module or imported name using as:
import numpy as np # common convention
import pandas as pd # common convention
import matplotlib.pyplot as plt # common convention
# now use the short name
from math import square_root as sqrt # rename on importWith built-in modules:
import datetime as dt
today = dt.date.today()
print(today) # 2026-06-02Use as when the module name is long, conflicts with something else, or has a widely-used conventional alias like np for numpy.
from module import * — import everything
from math import *
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
print(floor(3.9)) # 3This imports every public name from the module directly into your namespace.
Avoid import * in real code. It pollutes your namespace with names you did not ask for, makes it impossible to tell where a name came from, and can silently overwrite your own variables. Use it only in quick scripts or the interactive shell.
How Python finds modules
When you write import something, Python searches in this order:
This is why installing a package with pip makes it importable — pip puts it in site-packages where Python looks.
Importing your own files
Say you have two files in the same folder:
project/
├── main.py
└── helpers.pyhelpers.py:
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
PI = 3.14159main.py:
import helpers
print(helpers.greet("Ali")) # Hello, Ali!
print(helpers.add(3, 4)) # 7
print(helpers.PI) # 3.14159Or import specific things:
from helpers import greet, add
print(greet("Ali")) # Hello, Ali!
print(add(3, 4)) # 7name and if name == "main"
Every Python file has a special built-in variable called __name__. Its value depends on how the file is being used:
- When you run the file directly —
__name__is"__main__" - When the file is imported by another file —
__name__is the module's filename
# helpers.py
print(f"__name__ is: {__name__}")Run directly:
__name__ is: __main__Imported from another file:
__name__ is: helpersWhy this matters
Imagine helpers.py has some test code at the bottom:
# helpers.py
def greet(name):
return f"Hello, {name}!"
# test code
print(greet("Ali")) # you wrote this to test the functionNow when main.py imports helpers, that test print runs too — even though you did not want it to. That is a problem.
The fix — wrap any code you only want to run when the file is executed directly:
# helpers.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
if __name__ == "__main__":
# this only runs when you execute helpers.py directly
# it does NOT run when helpers is imported
print(greet("Ali"))
print(add(3, 4))Now importing helpers is clean — no unwanted output. But running helpers.py directly still runs your test code.
if __name__ == "__main__": is one of the most common Python patterns. You will see it in almost every Python file that is meant to be both importable and runnable. Always use it to protect your test or startup code.
Organizing imports — style guide
Python's official style guide (PEP 8) says imports should be grouped in this order, with a blank line between each group:
# 1. Standard library imports
import os
import sys
from datetime import datetime
# 2. Third-party imports (installed via pip)
import requests
import pandas as pd
# 3. Your own local imports
from helpers import greet
from utils import format_dateMost editors and tools like isort do this automatically.
Reloading a module
Normally Python loads a module once and caches it. If you change the module file and want to reload it without restarting Python:
import importlib
import helpers
# after changing helpers.py
importlib.reload(helpers)You will mostly use this in the interactive shell or Jupyter notebooks — not in regular scripts.
A real example
A project with a utility module:
utils.py:
def format_currency(amount, symbol="$"):
return f"{symbol}{amount:,.2f}"
def clamp(value, min_val, max_val):
"""Keep value between min and max."""
return max(min_val, min(value, max_val))
def percentage(part, total):
if total == 0:
return 0
return round((part / total) * 100, 1)
if __name__ == "__main__":
print(format_currency(1234567.89)) # $1,234,567.89
print(clamp(150, 0, 100)) # 100
print(percentage(45, 200)) # 22.5main.py:
from utils import format_currency, percentage
sales = 48750
target = 60000
print(f"Sales: {format_currency(sales)}")
print(f"Target: {format_currency(target)}")
print(f"Achievement: {percentage(sales, target)}%")Output:
Sales: $48,750.00
Target: $60,000.00
Achievement: 81.2%Summary
| Syntax | What it does |
|---|---|
import module | Import the whole module |
from module import name | Import a specific name |
from module import a, b | Import multiple names |
import module as alias | Import with a short name |
from module import * | Import everything (avoid) |
if __name__ == "__main__": | Run only when executed directly |