Modules and Imports
7 min ยท The Basics
What are Modules?
Modules are Python files containing functions, classes, and variables that you can reuse in your code. Python comes with a vast standard library of built-in modules that provide ready-to-use functionality for common tasks.
Using modules allows you to organize code into logical units, reuse code across projects, and leverage the work of others. Instead of writing everything from scratch, you can import modules and use their functionality.
Import Styles
Python offers several ways to import modules. Each has its use case:
Recommended Import Style
๐ก Best Practice
Use import module_name for most cases. It's clear where functions come from and avoids name conflicts. Only use from module import item when you need a specific function frequently.
โ ๏ธ Avoid Wildcard Imports
Never use from module import *. It makes code harder to read and can cause unexpected conflicts with your variable names.
Common Built-in Modules
Python's standard library includes hundreds of modules. Here are some of the most commonly used ones:
mathโ Mathematical functions and constants (sqrt, sin, cos, pi, e)randomโ Random number generation (randint, choice, shuffle)datetimeโ Date and time handling (date, time, datetime)osโ Operating system interface (file paths, environment variables)jsonโ JSON encoding and decoding (loads, dumps)sysโ System-specific parameters and functionsreโ Regular expressions for pattern matchingcollectionsโ Specialized container datatypes
Examples of Common Modules
Let's see some practical examples of using different modules:
Importing Multiple Modules
You can import multiple modules in your program. It's common to group imports at the top of your file:
Module Organization
Python conventions recommend organizing imports in this order:
Checking Available Functions
You can see what's available in a module using the dir() function:
Module vs Package
๐ Module vs Package
Module: A single Python file containing code (e.g., math.py)
Package: A directory containing multiple modules (e.g., datetime package has date, time modules)