Python

Python Modules and Packages — import, Aliases, and __name__

Every Python file is a module, and import is how one file uses the code in another. That one mechanism covers the standard library, packages you install, and the files in your own project. This guide shows the working core: importing a module and using its names, the from form and aliases, writing a module of your own and importing it, what __name__ holds in a file that is run and in a file that is imported, the guard that keeps run-only code out of an import, and how a folder becomes a package.

Written November 12, 2026 · Tested with Python 3.12.3 · 8 min read

By the end of this guide
  • The main program: importing a module
  • The from form and aliases
  • A module you write is an ordinary file
  • name in a file that is run

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

A module is one Python file. When a program imports a module, Python finds the file, runs it once, and binds the module name in the importing program. Every name defined at the top level of that file, each function, class, and variable, is then reachable through the module name. A package is a folder that holds related modules, so a larger library can split its code across files while still being imported under one top name. Nothing else is required: no registration, no build step, and no special header in the file.

The main program: importing a module

The import line names the module, and each use names the module first and then the item inside it:

Python
import math

print(math.sqrt(16))
print(math.floor(3.7))
print(math.ceil(3.2))
print(round(math.pi, 2))

The exact output:

Output
4.0
3
4
3.14

The name math is the module itself. The dot reaches inside it: math.sqrt is the square root function that the math module defines, and math.pi is a value it holds. Keeping the module name in front of each use makes the origin of every function plain in the reading, which matters once a program imports several modules that happen to define similar names. The module file runs only on the first import. A second import of the same module in the same program reuses the loaded result instead of running the file again.

The from form and aliases

Two variants reshape the names. The from form copies selected names out of the module into the importing program, so they are used bare. The as form gives a module, or a single name, a shorter local name:

Python
from math import sqrt, floor
import math as m

print(sqrt(25))
print(floor(9.8))
print(m.gcd(12, 18))

The exact output:

Output
5.0
9
6

Here sqrt and floor are used without the math prefix, while gcd is reached through the alias m. The from form reads well for a name used many times in one file. Its cost is that a reader can no longer tell from the call alone which module the bare name came from. The alias form keeps a prefix, only a shorter one. A related form, importing every name with a star, copies names the reader never sees listed anywhere in the file. Skip that form in programs you keep: an explicit list is the record of what a file depends on.

A module you write is an ordinary file

Your own module is a file with definitions in it, placed where Python can find it. The shortest way to see the whole mechanism is a program that writes a small module file and then imports it:

Python
from pathlib import Path
import sys

Path("helper.py").write_text("def triple(n):\n    return n * 3\n\nVALUE = 7\n")
sys.path.insert(0, ".")
import helper

print(helper.triple(4))
print(helper.VALUE)
print(helper.__name__)

The exact output:

Output
12
7
helper

In real project code you write helper.py with an editor instead of from inside a program, and the folder holding it is already on the search path, so the sys.path line is not needed. The steps are the same either way. The file defines a function and a value, the import runs the file, and both names are reachable through helper. The last line prints the module's own name, which Python stores on every module as name. That attribute is the subject of the next two sections, because its value depends on how the file was reached.

name in a file that is run

When you run a file directly, its name is the string "main" rather than the file's own name:

Python
def main():
    print("running as main")

print(__name__)
if __name__ == "__main__":
    main()

The exact output:

Output
__main__
running as main

The if line is the standard guard. Code under it runs only when the file itself is the program being run. Code outside the guard, the definitions and any top-level statements, runs in both cases: when the file is run and when another file imports it. Putting the program's entry work under the guard is what lets the same file serve as both a runnable program and an importable module.

An import does not run the guarded code

The other half of the guard shows when a file is imported. This program writes a module that prints a line at its top level and has a second line under the guard, then imports it:

Python
from pathlib import Path
import sys

Path("greeter.py").write_text('print("module loaded:", __name__)\nif __name__ == "__main__":\n    print("guarded")\n')
sys.path.insert(0, ".")
import greeter

print("imported")

The exact output:

Output
module loaded: greeter
imported

Two facts are visible in that output. The imported file's name is greeter, its own module name, not "main", so the guarded line never prints. And the top-level print does run, because importing runs the whole file once. That is why a module should hold definitions at its top level, not work: any statement placed there fires in every program that imports the module, at import time, before the importing program's own code continues.

A package is a folder of modules

A package groups modules under one folder name. The folder holds an init.py file, which may be empty, plus one file per module. This program builds a small package and imports a function from one module inside it:

Python
from pathlib import Path
import sys

pkg = Path("shop")
pkg.mkdir(exist_ok=True)
(pkg / "__init__.py").write_text("")
(pkg / "prices.py").write_text("def total(items):\n    return sum(items)\n")
sys.path.insert(0, ".")
from shop.prices import total

print(total([3, 4, 5]))
print(total([]))

The exact output:

Output
12
0

The import path reads as a path: shop is the package, prices is the module file inside it, and total is the function that file defines. The empty init.py marks the folder as a regular package and runs when the package is first imported, which is why packages can also use it to set up shared values. Splitting a project this way keeps each file small and gives every function an unambiguous full name, the package, the module, and the function, that no other part of the project can collide with.

The standard library is modules too

Nothing about the modules above is special to your own files. The standard library is a set of modules and packages shipped with Python, imported in the same way:

Python
import json

data = {"name": "bo", "tags": ["a", "b"]}
text = json.dumps(data, sort_keys=True)
print(text)
print(json.loads(text)["tags"])

The exact output:

Output
{"name": "bo", "tags": ["a", "b"]}
['a', 'b']

The json module turns a dictionary into a text form with dumps and parses that text back with loads. The pattern is the one this guide opened with: import the module, then reach its functions through its name. Installed packages from outside the standard library follow the same rule once they are on the search path. Learning the import forms once covers all three sources: your files, the standard library, and installed packages.

Which form for which job

Job Form Why
Use a module and keep origins plain import module Every use carries the module name as a prefix
Use one or two names many times from module import name The names read bare after an explicit list at the top
Shorten a long module name import module as short A prefix remains, only shorter
Split your own code across files One module per topic, imported by name Each file stays small and its names stay unambiguous
Keep run-only work out of imports The name guard Importing runs definitions only, never the entry work
Group related modules A package folder with init.py One top name covers the group, with modules inside

Checklist

  • Before importing a name with the from form, list it in the import line; never use the star form in a program you keep.
  • Before placing a statement at a module's top level, remember that it runs at import time in every importing program.
  • Before running entry work in a file that others may import, put that work under the name guard.
  • Before reaching for a helper from another file, import the module and call through its name, so the origin stays plain.
  • Before splitting a growing module, group the new files as a package instead of leaving loose modules with colliding names.
  • Before writing a function that Python may already ship, check the standard library modules; the import costs one line.

Sources

Keep Exploring