Importing Modules

Learn different ways to import modules in Python, including import, from...import, and import as statements.

Ali Berro

By Ali Berro

6 min read Section 4
From: Python Fundamentals: From Zero to Hero

Importing Modules

Python provides several ways to import modules and their contents. Understanding these different import methods helps you write clean, readable, and efficient code.

Basic Import: import

The simplest way to import a module is using the import statement:

basic-import.py
import math
# Access functions using module name
result = math.sqrt(16)
print(result) # 4.0
# Access constants
print(math.pi) # 3.141592653589793

Importing Multiple Modules

You can import multiple modules on separate lines or on one line:

multiple-imports.py
import math
import random
import datetime
# Or on one line
import math, random, datetime

Note

It’s generally better to import modules on separate lines for better readability.

Import with Alias: import ... as

You can give a module an alias (nickname) when importing:

import-as.py
import math as m
import datetime as dt
# Use the alias
print(m.sqrt(16)) # 4.0
print(dt.datetime.now()) # Current date and time

This is useful when:

  • Module names are long
  • You want to avoid naming conflicts
  • Following common conventions (e.g., import numpy as np)

From Import: from ... import

You can import specific items from a module:

from-import.py
from math import sqrt, pi, factorial
# Use directly without module name
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
print(factorial(5)) # 120

Importing Multiple Items

from-import-multiple.py
from math import sqrt, pi, factorial, sin, cos
print(sqrt(25)) # 5.0
print(sin(pi / 2)) # 1.0

Import All: from ... import *

You can import all names from a module using *:

import-all.py
from math import *
# All math functions available directly
print(sqrt(16)) # 4.0
print(pi) # 3.141592653589793
print(sin(pi / 2)) # 1.0

Warning

Avoid using import * in production code. It:

  • Pollutes the namespace
  • Makes it unclear where names come from
  • Can cause naming conflicts
  • Makes code harder to read and maintain

Combining Import Methods

You can combine from and as:

from-import-as.py
from math import sqrt as square_root, pi as PI
print(square_root(16)) # 4.0
print(PI) # 3.141592653589793

Import Order

Follow this import order (PEP 8 style guide):

  1. Standard library imports
  2. Related third-party imports
  3. Local application/library imports
import-order.py
# Standard library
import os
import sys
import math
# Third-party
import numpy as np
import pandas as pd
# Local
import my_module
from my_package import my_function

Importing from Packages

When importing from packages (directories with modules), use dot notation:

package-import.py
from my_package import my_module
from my_package.subpackage import another_module
# Or
import my_package.my_module

Conditional Imports

You can import modules conditionally:

conditional-import.py
try:
import optional_module
except ImportError:
optional_module = None
print("Optional module not available")
if optional_module:
optional_module.do_something()

Relative Imports

Within a package, you can use relative imports:

relative-import.py
# In a package module
from . import sibling_module # Same package
from .. import parent_module # Parent package
from ..sibling import other_module # Sibling package

Note

Relative imports can only be used within packages, not in scripts run directly.

Import Best Practices

  1. Use explicit imports: Prefer import module or from module import item
  2. Avoid import *: It makes code unclear and can cause conflicts
  3. Group imports: Group standard library, third-party, and local imports
  4. Use aliases for long names: import numpy as np is clearer than typing numpy everywhere
  5. Import at the top: Place imports at the beginning of your file
  6. Be specific: Import only what you need

Common Import Patterns

Pattern 1: Standard Library

pattern-standard.py
import math
import os
import sys

Pattern 2: Third-Party with Alias

pattern-third-party.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Pattern 3: Specific Functions

pattern-specific.py
from math import sqrt, pi
from datetime import datetime, timedelta

Pattern 4: Module with Alias

pattern-alias.py
import datetime as dt
import json as js

Import Examples

Example 1: Math Operations

import-example-1.py
import math
# Calculate circle area
radius = 5
area = math.pi * radius ** 2
print(f"Area: {area}")
# Calculate distance
distance = math.sqrt(3**2 + 4**2)
print(f"Distance: {distance}")

Example 2: Random Data

import-example-2.py
import random
# Generate random numbers
numbers = [random.randint(1, 100) for _ in range(5)]
print(numbers)
# Random choice
colors = ['red', 'green', 'blue']
print(random.choice(colors))

Example 3: Date and Time

import-example-3.py
from datetime import datetime, timedelta
# Current time
now = datetime.now()
print(f"Now: {now}")
# Future time
future = now + timedelta(days=7)
print(f"Future: {future}")

Exercises

Exercise 1: Basic Import

Import the math module and use it to calculate and print the square root of 25 and the value of pi.

Basic Import

Checks: 0 times
Answer:
import math
print(math.sqrt(25))
print(math.pi)

Exercise 2: Import with Alias

Import the datetime module with alias dt. Use it to get and print the current date and time.

Import with Alias

Checks: 0 times
Answer:
import datetime as dt
print(dt.datetime.now())

Exercise 3: From Import

Use from math import to import sqrt, pi, and factorial. Calculate and print: sqrt(36), pi, and factorial(4).

From Import

Checks: 0 times
Answer:
from math import sqrt, pi, factorial
print(sqrt(36))
print(pi)
print(factorial(4))

Exercise 4: Multiple Imports

Import both math and random modules. Use math to calculate sqrt(64), and random to generate a random integer between 1 and 10.

Multiple Imports

Checks: 0 times
Answer:
import math
import random
print(math.sqrt(64))
print(random.randint(1, 10))

Exercise 5: From Import with Alias

Use from datetime import datetime as dt to import datetime with alias. Get the current time and print it.

From Import with Alias

Checks: 0 times
Answer:
from datetime import datetime as dt
print(dt.now())

Course Progress

Section 59 of 61

Back to Course