Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 149 ยท Modules and the Standard Library

Modules and Imports

Learn how Python modules work. Use import, from ... import and aliases, write your own module, and understand the if __name__ == "__main__" idiom.

Once a program grows past a few dozen lines, keeping everything in one file gets messy. Python's answer is the module: a file of Python code that other code can load and reuse. Every .py file you write is already a module, and Python ships with hundreds of them in its standard library, ready to use with one line.

In this lesson you'll learn the different ways to import code, how Python finds modules, how to write a module of your own, and what the famous if __name__ == "__main__": line is for.

Importing a whole module

The simplest form is import followed by the module name. You then reach the module's contents with a dot, just like attributes on an object:

Python import a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dotted style (math.sqrt) costs a few extra characters, but it tells every reader exactly where a name came from. That's why it's the most common choice in real code.

A module only runs once per program, no matter how many times you import it. Python remembers loaded modules in a dictionary called sys.modules, and later imports simply reuse the cached object.

from ... import: pick specific names

When you need just a few names, from module import name copies them into your file so you can use them without the prefix:

Python from ... import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is handy for names you use constantly. The trade-off: a reader who sees floor(...) has to scroll up to learn where it came from, and a local variable named floor would quietly replace it.

Avoid from module import *. It dumps every public name into your file, so you can't tell where anything came from, and it can silently overwrite your own names. It's fine for quick experiments in the REPL, but not in code you keep.

Aliases with as

The as keyword gives a module or a name a different local name. Use it to shorten long names, follow a community convention, or avoid a clash:

Python Aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Some aliases are so common that everyone expects them: data scientists write import numpy as np and import pandas as pd. Outside such conventions, prefer clear names over clever abbreviations.

Which import style should you use?

Style Example Good for
Whole module import json Most code; keeps names clearly labeled
Specific names from pathlib import Path Names you use often and that are unambiguous
Alias import datetime as dt Long names or established conventions

The style guide PEP 8 also asks you to put imports at the top of the file, one module per line, grouped as standard library first, then third-party packages, then your own modules.

Writing your own module

A module is nothing more than a .py file. If you save a file called geometry.py, any script in the same folder can import geometry. On your computer you'd create the file in your editor. Here in the browser, Python has an in-memory file system, so the demo writes the file with pathlib and then imports it:

Python Create and import a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two lines after write_text() are only needed because the file was created while Python was already running: importlib.invalidate_caches() makes Python notice the new file, and removing "geometry" from sys.modules (explained below) throws away a cached copy if you edit the code and run it again. In a normal project the file exists before you start Python, so you just write import geometry.

A module's top-level names (PI, circle_area, square_area) become its attributes. Its docstring, the string on the first line, is available as __doc__, which is what help(geometry) shows.

How Python finds modules

When you write import geometry, Python searches a list of folders stored in sys.path, in order, and uses the first match:

  1. The folder of the script you ran (or the current folder in the REPL).
  2. Folders listed in the PYTHONPATH environment variable, if any.
  3. The standard library.
  4. The site-packages folder where installed third-party packages live.
Python Inspect sys.path and sys.modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Press Run a second time and the first answer changes to True. This editor keeps Python loaded between runs, so the module from your previous run is still cached, exactly like a second import inside one long-running program.

Because your own folder comes first, a file of yours can shadow a standard module.

Don't name your files after standard modules. A script called random.py or json.py gets imported instead of the real module, and you'll see confusing errors like "module 'random' has no attribute 'randint'". Rename the file (and delete any __pycache__ folder next to it).

The __name__ == "__main__" idiom

Every module has a variable called __name__. When a file is imported, __name__ holds the module's name. When the file is run directly as a script, Python sets it to the special string "__main__". That lets one file act as both a reusable module and a runnable program:

Python
# temperature.py
def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32


def main():
    for c in (0, 20, 37, 100):
        print(f"{c} ยฐC = {to_fahrenheit(c)} ยฐF")


if __name__ == "__main__":
    main()

Running python temperature.py prints the table. Writing import temperature in another file gives you to_fahrenheit without printing anything.

You can watch both cases in the browser. The standard runpy module runs a module the same way python greeter.py would, with __name__ set to "__main__":

Python __name__ in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When imported, the module's own __name__ is "greeter", so its demo block is skipped. When run as a script, the same file sees "__main__" and runs the demo. Write your reusable functions at the top level and put "do something now" code under the if guard.

Reloading and exploring modules

Two built-ins help you explore an unfamiliar module:

  • dir(module) lists the names a module defines.
  • help(module) or help(module.function) prints its documentation.

If you edit a module while a REPL session is running, import won't pick up the change, because the module is cached. importlib.reload(module) runs it again. In scripts you rarely need this; just restart the program.

Python Explore a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Names starting with an underscore are treated as private by convention: they're accessible, but the module's author is signaling "not part of the public interface".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After from math import sqrt, how do you call the square root function?

    from ... import copies the name into your file, so you call it directly. The name math itself is not defined by that statement.
  2. 2. What is the value of __name__ inside a file that you run directly with python app.py?

    The file being run as a script always gets __name__ == "__main__". When it is imported instead, __name__ is the module name, "app".
  3. 3. You saved your script as random.py and now random.randint fails. Why?

    Python searches the script's own folder first, so it imports your file instead of the real module. Rename your file.
  4. 4. What happens if two different files both run import json in the same program?

    Modules are cached in sys.modules after the first import, so later imports are fast and share the same module object.

Summary

  • A module is a .py file; the standard library offers hundreds of them.
  • import module keeps names prefixed (math.pi); from module import name brings names in directly; as creates an alias.
  • Avoid from module import * and don't name your files after standard modules.
  • Python looks for modules in the folders listed in sys.path and caches loaded modules in sys.modules.
  • if __name__ == "__main__": runs code only when the file is executed as a script, not when it's imported.
  • dir() and help() let you explore any module.

Next: Packages and pip, where you'll group modules into packages and install code other people have published.