Learn by reading through in order

Modules and Packages — Importing from Other Files

Learn the differences between Python modules, packages, and libraries, plus how the import statement pulls functions in from other files.

Python applications are usually built by splitting work across multiple files and wiring them together. This article walks through the units called modules and packages, plus how the import statement pulls features in from another file.

Module vs. Package vs. Library

Python organizes code in three sizes: module → package → library. A module is a single .py file, a package is a folder of modules, and a library is the next level up — a distributable bundle.

Module / Package / Library Hierarchy
ModuleOne .py filePackageFolder with __init__.pyLibrarypandas / NumPy / etc.groupsships as
Files (modules) gather into folders (packages), and several packages get distributed together as one library (pandas, NumPy, etc.).
UnitWhat it isExample
ModuleA single .py filemath_utility.py
PackageA folder containing __init__.pymy_app/database/
LibraryA distribution of one or more packagespandas / NumPy / requests

Standard Library vs. Third-Party Library

Python ships with a standard library out of the box, and there are third-party libraries you install on top. Standard ones like math, os, and json work with just import. Third-party ones like pandas or requests need pip install package_name first.

TypeInstallExamples
Standard libraryBundled with Python (no install)math / os / sys / json / datetime
Third-party libraryAdd via pip installpandas / numpy / requests

Try the standard math library.

① Print the integer ceiling of 1.7 with math.ceil(1.7).

② Print the square root of 3 with math.sqrt(3).

(If you run it correctly the explanation appears below.)

Python Editor

Run code to see output

Importing Your Own Modules

You can import your own .py files just like the standard library. When running Python locally, drop main.py and the file you want to import (math_utility.py) into the same folder — that's it. Files in the same folder load with just import math_utility from main.py (no .py suffix in the import statement).

Local Layout (Files Side by Side)
my_project/ ← the project folder
  • main.py — the entry point. Starts with import math_utility
  • math_utility.py — the module that defines add() / multiply()
Place main.py and math_utility.py in the same folder. Python checks the folder of the running file first, so import math_utility finds the neighbor right away — no subfolder needed.
From import to Calling a Function
main.pyimport math_utilityPython loadsthe file fromthe same foldermath_utility.add()math_utility.multiply()are callableloaddone
When import math_utility runs, Python loads math_utility.py from the same folder. After that, you can call its functions as math_utility.add(...) with the module name in front.

math_utility.py is attached on the left (open it from 📂 Files to inspect).

① Load it with import math_utility.

Intentionally call add(10, 20) without the module prefix and confirm with try/except that you get a NameErrorimport math_utility only brings the name math_utility itself into main's scope, so add is not directly callable.

③ Then print math_utility.add(10, 20) and math_utility.multiply(5, 5) with the module name prefix — the correct way to call them.

Python Editor

Run code to see output

import Runs the Whole File Once

When you write import math_utility, Python executes math_utility.py from top to bottom one time. Function definitions (def) are registered in memory at that moment, so you can later call them as math_utility.add(...). The bodies of those functions don't run at import time — only the code outside any function (the module's top level).

What Loading an External File Looks Like
main.pyimport math_utilitymath_utility.pyruns top to bottommath_utility.add()is callableloadafter
The instant main.py hits import math_utility, Python runs math_utility.py top to bottom. def definitions are registered in memory and become callable as math_utility.add(...) afterward.

Don't Run Heavy Work at Module Top Level

Top level means code that sits at the outermost indent — outside any function or class. Python runs it from top to bottom whenever the module is imported. Putting heavy work there (DB connections, loading huge files, infinite loops) means just importing the module takes forever. Keep the heavy logic inside functions and leave only definitions and minimal initialization at top level.

Telling Direct Run from Import — __name__

Python files come in two flavors: scripts run directly (you launch them with python xxx.py) and modules imported by something else. The same file can play either role, and you often need to tell which is happening — for example, "only run a smoke test when the file is run directly".

The check uses the special variable __name__ that Python sets automatically. When the file is run directly, __name__ is "__main__". When the file is imported, __name__ is the module name (the filename). Code inside if __name__ == "__main__": only runs in the first case.

__name__ Changes Depending on How the File Runs
__name__(special variableset by Python)Run directlypython xxx.py__name__= "__main__"Imported byanother file__name__= "xxx"(module name)
The auto-set special variable __name__ is "__main__" when you run the file directly (python xxx.py), and the module name (filename) when another file imports it.
# math_utility.py
def add(a, b):
    return a + b


# Smoke test only when run directly
if __name__ == "__main__":
    print("check:", add(10, 20))   # 30

# When another file does `import math_utility`,
# the if block above doesn't run — only the add function is exposed.

The attached math_utility_2.py defines a show_name() function that prints its own __name__, plus an if __name__ == "__main__": block at the bottom (open it from 📂 Files to look).

① From the main side, import math_utility_2 and print main's __name__.

② Call math_utility_2.show_name() and check what __name__ looks like from the imported side.

Python Editor

Run code to see output

Combining Several of Your Own Modules

In real applications you typically split functions into separate files by responsibility and pull them all in from main.py. For example, input checks live in validator.py, display formatting in formatter.py. With responsibilities split this way, changes to formatting only touch formatter.py — main.py and validator.py stay untouched.

main.py Combining Two of Your Own Modules
main.pyimport validatorimport formattervalidator.pyis_valid_price()formatter.pyformat_price()importimport
main.py imports two modules with import validator and import formatter, then combines their functions to do one job.

Fill in the attached validator.py and formatter.py, then import both from main.py.

① In validator.py, implement is_valid_price(price) — return True if price is a positive int, False otherwise.

② In formatter.py, implement format_price(price) — take an int, add a 5% surcharge with int(price + price * 0.05), and return a string like "with tax: $1575".

③ In main.py, import both. Decide whether price = 1500 is valid, format it, and print the result.

Python Editor

Run code to see output

This article covered the module / package / library hierarchy, how import pulls functions from other files, what runs at import time, the __name__ == "__main__" pattern for telling direct runs from imports, and the multi-module split where each file owns one responsibility. The next article digs into packages and the __init__.py file.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Which mapping of module / package / library is correct?

Q2math_utility.py has print("hello") written at the top level. What appears on screen when another file does import math_utility?

Q3What's the right pairing for direct run vs import of this code?
if __name__ == "__main__":
print("hello")