Lesson 1 of 6 · Modules and the Standard Library · 3 min read · Updated

Modules and import

Using code from another file — Python's own or yours — and the __name__ check.

A module is simply a Python file. import runs it once and gives you access to what it defines. Python ships with hundreds of them — the standard library — so a great deal is already written for you.

python
import math
print(math.sqrt(16))

from math import pi, floor
print(floor(pi * 100) / 100)

import statistics as stats
print(stats.mean([72, 85, 91]))
Output
4.0
3.14
82.66666666666667
  • import math — use names with the module prefix: math.sqrt.
  • from math import pi — bring chosen names in directly.
  • import statistics as stats — a shorter nickname for a long module name.

Warning

Avoid from math import *. It pours every name into your file, and a later import can silently replace one you were using. The prefix form also tells the reader where each name came from.

Your own module

python
# greetings.py
def hello(name):
    return f"Vanakkam, {name}!"

# main.py — in the same folder
import greetings
print(greetings.hello("Kavya"))

Put functions in greetings.py, and any file in the same folder can import greetings. Do not name your file after a standard module — a file called math.py or random.py hides the real one.

Run as a program, or import as a module

python
def main():
    print("Running as a program")

print(__name__)
if __name__ == "__main__":
    main()
Output
__main__
Running as a program

Every module has a __name__. When you run the file directly it is "__main__"; when it is imported it is the module's name. The check at the bottom lets one file work both ways: run it and main() starts; import it and you just get its functions.

Note

dir(math) lists everything a module offers and help(math.sqrt) explains one item — both work at the interactive prompt without leaving Python.

After from math import sqrt, how do you call it?

Try this now

  1. Move your temperature-conversion functions into convert.py and import them from another file.
  2. Add a __name__ == "__main__" block to convert.py that runs a quick self-test, and check it does not run on import.

Create a free account to save your progress, or sign in.