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:
import math
# Access functions using module nameresult = math.sqrt(16)print(result) # 4.0
# Access constantsprint(math.pi) # 3.141592653589793Importing Multiple Modules
You can import multiple modules on separate lines or on one line:
import mathimport randomimport datetime
# Or on one lineimport math, random, datetimeNote
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 math as mimport datetime as dt
# Use the aliasprint(m.sqrt(16)) # 4.0print(dt.datetime.now()) # Current date and timeThis 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 math import sqrt, pi, factorial
# Use directly without module nameprint(sqrt(16)) # 4.0print(pi) # 3.141592653589793print(factorial(5)) # 120Importing Multiple Items
from math import sqrt, pi, factorial, sin, cos
print(sqrt(25)) # 5.0print(sin(pi / 2)) # 1.0Import All: from ... import *
You can import all names from a module using *:
from math import *
# All math functions available directlyprint(sqrt(16)) # 4.0print(pi) # 3.141592653589793print(sin(pi / 2)) # 1.0Warning
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 math import sqrt as square_root, pi as PI
print(square_root(16)) # 4.0print(PI) # 3.141592653589793Import Order
Follow this import order (PEP 8 style guide):
- Standard library imports
- Related third-party imports
- Local application/library imports
# Standard libraryimport osimport sysimport math
# Third-partyimport numpy as npimport pandas as pd
# Localimport my_modulefrom my_package import my_functionImporting from Packages
When importing from packages (directories with modules), use dot notation:
from my_package import my_modulefrom my_package.subpackage import another_module
# Orimport my_package.my_moduleConditional Imports
You can import modules conditionally:
try: import optional_moduleexcept 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:
# In a package modulefrom . import sibling_module # Same packagefrom .. import parent_module # Parent packagefrom ..sibling import other_module # Sibling packageNote
Relative imports can only be used within packages, not in scripts run directly.
Import Best Practices
- Use explicit imports: Prefer
import moduleorfrom module import item - Avoid
import *: It makes code unclear and can cause conflicts - Group imports: Group standard library, third-party, and local imports
- Use aliases for long names:
import numpy as npis clearer than typingnumpyeverywhere - Import at the top: Place imports at the beginning of your file
- Be specific: Import only what you need
Common Import Patterns
Pattern 1: Standard Library
import mathimport osimport sysPattern 2: Third-Party with Alias
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltPattern 3: Specific Functions
from math import sqrt, pifrom datetime import datetime, timedeltaPattern 4: Module with Alias
import datetime as dtimport json as jsImport Examples
Example 1: Math Operations
import math
# Calculate circle arearadius = 5area = math.pi * radius ** 2print(f"Area: {area}")
# Calculate distancedistance = math.sqrt(3**2 + 4**2)print(f"Distance: {distance}")Example 2: Random Data
import random
# Generate random numbersnumbers = [random.randint(1, 100) for _ in range(5)]print(numbers)
# Random choicecolors = ['red', 'green', 'blue']print(random.choice(colors))Example 3: Date and Time
from datetime import datetime, timedelta
# Current timenow = datetime.now()print(f"Now: {now}")
# Future timefuture = 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
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
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
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
import mathimport 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
from datetime import datetime as dt
print(dt.now())