Fundamentals 5 min read

Understanding Python's import and from Statements: Usage Scenarios and Best Practices

This article explains the differences between Python's import and from statements, detailing their syntax, use cases such as importing whole modules, specific objects, setting aliases, and best practices for writing clear, efficient code.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python's import and from Statements: Usage Scenarios and Best Practices

In Python, modules are imported using the import and from keywords, each suited to different scenarios.

The import statement loads an entire module, allowing access to its attributes via module.name. It is useful when multiple functions or constants from the same module are needed, and it avoids naming conflicts by requiring the module prefix.

Examples:

import math
print("圆周率的值是:", math.pi)
print("2的平方根是:", math.sqrt(2))

Aliases can be set with as to shorten long module names or avoid conflicts:

import numpy as np
print("numpy的版本是:", np.__version__)

Standard library modules such as datetime are typically imported with import:

import datetime
now = datetime.datetime.now()
print("当前时间是:", now)

The from statement imports specific objects from a module, reducing namespace clutter when only a few items are required.

Examples:

from math import sqrt
print("3的平方根是:", sqrt(3))

Multiple objects can be imported at once:

from datetime import datetime, timedelta
now = datetime.now()
print("当前时间是:", now)
later = now + timedelta(days=1)
print("明天的时间是:", later)

Using from module import * imports all objects but is discouraged due to possible name collisions.

from math import *
print("sin(π/2)的值是:", sin(pi / 2))

The same approach applies to custom modules:

# my_module.py
def greet():
    print("Hello, world!")
from my_module import greet
greet()

Best practices: use import when needing many features from a module, use from when only a few are needed, and avoid from ... import * to prevent naming conflicts. Proper use of these statements leads to clearer, more efficient Python code.

PythonBest PracticesModules@ImportFROM
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.