Import Statements

📦 Python comes with many built-in modules and also allows you to use external packages. To use code from other modules or libraries, you use import statements.

1 import a Module

Import the whole module and access functions or classes with dot notation.

import math

print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.141592653589793
4.0
3.141592653589793

2 from ... import ...

Import specific parts (functions, classes, variables) from a module directly.

from math import sqrt, pi

print(sqrt(25))  # 5.0
print(pi)        # 3.141592653589793
5.0
3.141592653589793

3 Aliasing with as

Use as to give a module or function an alias—useful for shortening long names.

import numpy as np

print(np.array([1, 2, 3]))  # [1 2 3]
[1 2 3]
from math import factorial as fact

print(fact(5))  # 120
120

4 Wildcard Import (*)

Import everything from a module (not recommended in most cases).

from math import *

print(sin(pi / 2))  # 1.0
1.0

Avoid using * in production code—it can pollute your namespace and create conflicts.

5 Importing Custom Modules

You can also import your own .py files as modules.

Suppose you have a file myutils.py:

## |- myutils.py <- here
def greet():
    print("Hello from myutils!")

You can import and use it:

## |- myutils.py
## |_ python-advanced.py <- here
import myutils
myutils.greet()  # Hello from myutils!
Hello from myutils!

6 Conditional Imports

You can import modules inside functions or conditionally.

def use_math(number):
    import math
    print(math.sqrt(number))  # 4.0

use_math(16)
4.0

Common Errors

Some frequent errors encountered when dealing with Import Statements in Python.

import notamodule 
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[9], line 1
----> 1 import notamodule 

ModuleNotFoundError: No module named 'notamodule'
from math import donut
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[10], line 1
----> 1 from math import donut

ImportError: cannot import name 'donut' from 'math' (unknown location)