Skip to content
PythonModules, Files, and Errorsbeginner22 min read

Importing Modules

Import modules, use aliases, import specific names, and work with Python's standard library.

In this lesson, you will learn

  • ✓Explain what a module is and why Python programs import modules.
  • ✓Use import, import with an alias, and from-import syntax correctly.
  • ✓Access functions and constants from standard-library modules.
  • ✓Trace an import statement and predict the output of a program that uses an imported function.
  • ✓Recognize common import errors and avoid module naming conflicts.
  • ✓Choose an appropriate import style for a small Python program.

1. What is a module?

A Python module is a unit of reusable code, usually stored in a file with a .py extension. A module can contain function definitions, class definitions, variable assignments, and other statements.

Python's standard library provides many modules that you can use without writing their functionality yourself. For example, math provides mathematical functions and constants, while random provides tools for generating pseudorandom values.

The import statement makes a module available to your program. With import math, the name math refers to the imported module, and you can access its members using dot notation, such as math.sqrt(81).

Importing a module does not automatically place every name inside that module directly into your current namespace. With import math, you normally access the square-root function as math.sqrt rather than simply sqrt.

Import and use the math module

Import and use the math module
python
import math
 
print(math.sqrt(81))
print(math.pi)
Output
9.0 3.141592653589793

The first statement imports the math module and binds the name math in the current scope. math.sqrt refers to the square-root function provided by that module. math.sqrt(81) returns 9.0, a floating-point value. math.pi accesses the module's approximation of pi. The two print calls display their results on separate lines.

Note

The date example uses a fixed date so its output is predictable. The standard library also contains functions for working with the actual current date and time.

2. Import styles and aliases

Python supports several ways to import module functionality. The best choice depends on whether you want to access several members through a module name or use a small number of specific names directly.

With import math, you access members as math.sqrt() or math.ceil(). This style makes it clear which module provides each member.

With import math as m, you create the local alias m for the imported module. You then access members through m, as in m.sqrt(). An alias changes the name used in your code; it does not rename the module itself.

With from math import sqrt, you import the name sqrt directly into the current scope. You can then call sqrt(81) without writing math.sqrt().

With from math import sqrt as square_root, you import the function under the local name square_root. Aliases can be useful when they improve clarity or prevent a naming conflict.

Avoid from module import * in ordinary beginner code. Wildcard imports can introduce many names into the current scope, making it harder to identify where a name came from and increasing the chance of name conflicts.

Import a module with an alias

Import a module with an alias
python
import math as m
 
print(m.ceil(2.1))
print(m.floor(2.9))
Output
3 2

The alias m refers to the imported math module. m.ceil(2.1) returns the smallest integer greater than or equal to 2.1, which is 3. m.floor(2.9) returns the largest integer less than or equal to 2.9, which is 2. The results are integers, so the output does not include decimal places.

Note

Use the module-qualified style when it improves clarity. Import specific names when that makes a small program easier to read, and use aliases only when they are helpful.

3. Understand an import step by step

When Python executes an import statement, it locates the requested module, loads it if necessary, and makes its module object available through the imported name. The exact loading process depends on the module and Python's import system.

The first import of a module normally executes its module-level code. In the same interpreter, subsequent imports generally reuse the module object already stored in sys.modules rather than executing the module from scratch again.

After importing a module, Python does not run every function defined in it automatically. A function body normally runs when that function is called, although other statements at module level execute as part of loading the module.

When reading an import example, identify the imported name first, then follow the expression that accesses a module member, and finally trace the function call and displayed result.

Trace an imported function call

Trace an imported function call
python
import math
 
number = 25
result = math.sqrt(number)
print(result)
Output
5.0

Python imports math and binds the name math. The assignment number = 25 binds number to the integer 25. Python evaluates math.sqrt(number), calls the imported function with 25, and receives 5.0. The returned value is assigned to result. print(result) displays 5.0.

Note

An import statement usually produces no visible output by itself. Any displayed output in these examples comes from print calls.

4. How Python finds modules

Python must locate a module before it can import it. The import system searches using its configured import machinery and search path. For a typical beginner program, relevant locations can include the script's directory, configured paths in sys.path, the standard library, and installed packages.

The exact search path depends on how Python is launched, the environment, and the module being imported. You can inspect sys.path to see the import search path for the current interpreter.

A file in your project can also be imported as a module when Python can locate it. For example, if helpers.py is importable, another file can use import helpers and call helpers.some_function().

Avoid naming your own files after standard-library modules or other important modules you intend to import. A local file named math.py, for example, can interfere with importing the expected math module, depending on the execution environment and import path.

If Python cannot locate the requested module, it raises ModuleNotFoundError. This often means the module name is misspelled, the file is not in a searched location, or a required third-party package is not installed in the active environment.

Import a module from your own project

Import a module from your own project
python
# helpers.py
 
def double(number):
return number * 2
 
# main.py
import helpers
 
print(helpers.double(6))
Output
12

This example represents two separate files in the same project directory: helpers.py and main.py. helpers.py defines the function double. Defining the function does not print anything. When main.py imports helpers, Python must be able to locate helpers.py on its import path. The expression helpers.double(6) calls the imported function with 6. The function returns 12, which print displays.

Caution

The two-file example is illustrative, not one file to run unchanged: save the helper definition in helpers.py and the importing code in main.py. Both files must be arranged so that Python can find helpers.

5. Common import errors and good practices

A ModuleNotFoundError usually means Python could not find the requested module. Check the spelling, whether the module is part of the standard library or a third-party package, and whether the correct Python environment is being used.

An ImportError can occur when Python finds a module but cannot import the requested name from it. For example, the name may not exist in that module or may not be available under the expected name.

A circular import can occur when modules depend on each other in a way that causes one module to be imported before it has finished initializing. This is a more advanced issue, but it is one reason to keep module dependencies clear.

Choose descriptive file names for your own modules, use consistent import styles, and avoid unnecessary wildcard imports. If an import fails, read the exception and traceback rather than changing unrelated code at random.

Standard-library modules are included with Python, while third-party packages may need to be installed separately. Do not assume every module found in an online example is available in a fresh Python installation.

Handle a missing optional module

Handle a missing optional module
python
try:
import module_that_does_not_exist_12345
except ModuleNotFoundError:
print('Module not found')
Output
Module not found

The import requests a deliberately nonexistent module name. Python raises ModuleNotFoundError when it cannot locate the module. The except block catches that specific exception and prints Module not found. The example demonstrates exception handling. In real code, do not silently hide a missing dependency that the program actually requires.

Note

For required dependencies, fix the import problem rather than pretending the dependency is available. Exception handling is appropriate when a missing module is an expected and deliberately supported condition.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming import math makes sqrt available as a bare name.

Why it happens: import math binds the module name math; use math.sqrt(25) unless sqrt was imported directly with from math import sqrt.

Incorrect Approach
script.py
python
Assuming import math makes sqrt available as a bare name.
Correct Solution
script.py
python
Use math.sqrt() after import math, or explicitly import the function with from math import sqrt.

Key takeaway: Use math.sqrt() after import math, or explicitly import the function with from math import sqrt.

#2 Confusing a module alias with a new module.

Why it happens: An alias is another local name referring to the imported module or object; it does not create a separate copy of the module.

Incorrect Approach
script.py
python
Confusing a module alias with a new module.
Correct Solution
script.py
python
In import math as m, m is simply the local name used to refer to the imported math module.

Key takeaway: In import math as m, m is simply the local name used to refer to the imported math module.

#3 Using wildcard imports without understanding which names they introduce.

Why it happens: Wildcard imports can introduce unexpected names and make it harder to identify where a name came from.

Incorrect Approach
script.py
python
Using wildcard imports without understanding which names they introduce.
Correct Solution
script.py
python
Prefer import module or from module import specific_name so the source of each name remains clear.

Key takeaway: Prefer import module or from module import specific_name so the source of each name remains clear.

#4 Assuming every module is part of the Python standard library.

Why it happens: The standard library ships with Python, but third-party packages must usually be installed separately.

Incorrect Approach
script.py
python
Assuming every module is part of the Python standard library.
Correct Solution
script.py
python
Check whether the module is included with Python or is a third-party dependency that must be installed separately.

Key takeaway: Check whether the module is included with Python or is a third-party dependency that must be installed separately.

#5 Naming a project file after a module that the program needs to import.

Why it happens: Python searches import paths for modules, so a local file with the same name can shadow the intended standard-library or installed package.

Incorrect Approach
script.py
python
Naming a project file after a module that the program needs to import.
Correct Solution
script.py
python
Choose distinct file names to reduce the risk of shadowing standard-library modules or other dependencies.

Key takeaway: Choose distinct file names to reduce the risk of shadowing standard-library modules or other dependencies.

#6 Treating ModuleNotFoundError and ImportError as interchangeable in every situation.

Why it happens: ModuleNotFoundError usually means Python cannot find a requested module, while ImportError can occur when a module is found but a requested name or import cannot be loaded.

Incorrect Approach
script.py
python
Treating ModuleNotFoundError and ImportError as interchangeable in every situation.
Correct Solution
script.py
python
ModuleNotFoundError indicates that a requested module could not be found. ImportError is broader and can also occur when a requested name cannot be imported.

Key takeaway: ModuleNotFoundError indicates that a requested module could not be found. ImportError is broader and can also occur when a requested name cannot be imported.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a module in Python, and why do we import modules?
Answer:
A module is a unit of reusable Python code, usually stored in a .py file. Importing lets a program reuse functionality defined in another module, including functions, classes, variables, and standard-library features.
Q2:What is the difference between import math and from math import sqrt?
Answer:
import math binds the module name math, so the square-root function is accessed as math.sqrt(). from math import sqrt binds the name sqrt directly in the current scope, so it can be called as sqrt().
Q3:What is an import alias?
Answer:
An alias is an alternative local name introduced during an import. For example, import math as m lets the program use m.sqrt(). The alias changes the name used in the current scope, not the underlying module.
Q4:What is the difference between the standard library and third-party packages?
Answer:
The Python standard library is distributed with Python. Third-party packages are developed and distributed separately and may need to be installed in the environment being used. Availability depends on the Python installation and environment.
Q5:What is ModuleNotFoundError, and how would you troubleshoot it?
Answer:
ModuleNotFoundError means Python could not locate a requested module. Check the spelling, whether the module is built into the standard library or is a third-party dependency, whether it is installed in the active environment, and whether the import search path is appropriate.
Q6:Why should wildcard imports usually be avoided?
Answer:
A wildcard import can introduce many names into the current namespace, obscure their origins, and cause name conflicts. Importing a module or specific names generally makes code easier to read and maintain.

Key takeaways

  • A module is a reusable unit of Python code, usually stored in a file.
  • Use import module to access members through the module name, such as math.sqrt().
  • Use import module as alias when a shorter or clearer local name is useful.
  • Use from module import name to access a specific imported name directly.
  • Avoid unnecessary wildcard imports because they can obscure where names originate.
  • Python searches its configured import path to locate modules.
  • A local file named after a module can interfere with imports by shadowing the intended module.
  • ModuleNotFoundError indicates that Python could not locate a requested module; check the name, environment, and search path.
  • Module-level code executes when a module is loaded, but function bodies normally execute only when those functions are called.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: