Syntax
import module\nfrom module import nameExamples
Basic Import
Importing an entire module and accessing its contents with dot notation.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793Importing Specific Names
Importing only the specific functions or classes you need, used without the module prefix.
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793Import with an Alias
Renaming an import with 'as', commonly used for long module names or established conventions.
import numpy as np
import pandas as pd
# Common in data science code:
# arr = np.array([1, 2, 3])
# df = pd.DataFrame({"a": [1, 2, 3]})
from datetime import datetime as dt
now = dt.now()
print(now)Importing from Your Own Files
Importing functions or classes defined in another file within your own project.
# In a file called helpers.py:
# def greet(name):
# return f"Hello, {name}!"
# In your main file:
from helpers import greet
print(greet("John"))Best practices
- Use 'import module' when you use many things from that module, and 'from module import x' when you only need a couple of specific names
- Avoid 'from module import *' - it pollutes your namespace and makes it unclear where a name actually came from
- Follow standard aliasing conventions when they exist (numpy as np, pandas as pd) so your code is instantly familiar to other Python developers
- Group imports at the top of the file: standard library imports first, then third-party packages, then your own local modules
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference