Skip to content

Importing Modules

In Python, modules allow you to organize and reuse your code. A module is simply a .py file that contains functions, classes, or variables that you can use in other programs. Importing modules is a fundamental practice for writing clean, maintainable, and scalable code.


  • Reuse: Use already written functions and classes, avoiding repeated code.
  • Organization: Divide your project into smaller, more manageable files.
  • Access to tools: Take advantage of Python’s vast standard library and external packages.

Python includes a large number of ready-to-use modules. For example, to work with dates you can import the datetime module:

Importing a Standard Module
import datetime
today = datetime.date.today()
print('Today's date is:', today)

You can import only what you need from a module:

Importing a Specific Function
from math import sqrt
print(sqrt(16)) # 4.0

Sometimes an alias is used to shorten the module name:

Importing with Alias
import numpy as np
array = np.array([1, 2, 3])
print(array)

If you have a file named utilities.py in your project, you can import it like this:

Importing a Custom Module
import utilities
utilities.my_function()

  • Import only what you need.
  • Use aliases (as) for long or common names.
  • Keep your imports at the beginning of the file.

  • Modules help you organize and reuse code in Python.
  • You can import standard, external, or custom modules.
  • Use the different forms of import according to your needs.

Ready to test? Try importing the random module and generate a random number.