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("Fola"))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
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.