Python Modules

A module is a Python file whose functions, classes, and variables you can reuse in other programs by importing it.

What is a module?

A module is simply a file with a .py extension that contains Python definitions and statements. Splitting a program into modules keeps related code together, avoids repetition, and lets you share functionality between several projects. Python ships with a large standard library of ready-made modules, and you can also write your own or install third-party ones.

To use the code inside a module you bring it into your current file with the import keyword. Once imported, you access the names it defines using dot notation, such as module_name.function_name().

Creating and using your own module

# Save this as greetings.py
def welcome(name):
    return "Hello, " + name + "!"

# In another file, import and use it
import greetings

print(greetings.welcome("Priya"))
# Output: Hello, Priya!

Different ways to import

  • import module — loads the whole module; access names with module.name.
  • import module as alias — gives the module a shorter local name.
  • from module import name — pulls a single name directly into your file.
  • from module import name as alias — imports one name under a different label.
  • from module import * — imports everything, but this is discouraged because it can hide where names come from.

Importing specific names and aliases

# Import a single function
from math import sqrt
print(sqrt(16))        # 4.0

# Import a module under a shorter alias
import datetime as dt
now = dt.datetime.now()
print(now.year)
Note: Every module has a built-in __name__ variable. Use the dir() function, like dir(math), to list all the names a module defines without leaving your program.
StatementHow you call sqrt afterwards
import mathmath.sqrt(9)
import math as mm.sqrt(9)
from math import sqrtsqrt(9)
from math import sqrt as ss(9)

Python only runs a module's top-level code the first time it is imported during a session; later imports reuse the already-loaded version. Because of this, keep code that should only run when the file is executed directly inside an if __name__ == "__main__": block.

Exercise: Python Modules

What statement do you use to bring a module's code into your current script?