How to import modules

Import a module

An import loads a module and binds its name. Access members with dot notation, which keeps their origin visible.

import math

radius = 3
area = math.pi * math.pow(radius, 2)
print(area)

Import selected names

A from import can be convenient for frequently used names. Aliases resolve naming conflicts or shorten established long names.

from random import randint
import statistics as stats

values = [randint(1, 10) for _ in range(5)]
print(values)
print(stats.mean(values))

Create a local module

Put reusable definitions in helpers.py, then import it from another file in the same directory. Avoid naming files after standard modules such as json.py.

# helpers.py
def double(value):
    return value * 2

# app.py
import helpers
print(helpers.double(6))

Control script-only code

The main guard runs code when a file is executed directly but not when it is imported. This lets one file serve as both module and script.

def main():
    print("Running as a script")

if __name__ == "__main__":
    main()