Modules and Packages
Introduction to Modules and Packages
Modules are Python files containing functions, classes, and variables that you can import and use in other programs. Packages are collections of modules organized in directories. Using modules and packages helps organize code, avoid repetition, and build on others' work.
Python comes with a vast standard library of modules, and you can also create your own modules or install third-party packages.
Importing Modules
Use the import statement to use modules in your code:
Common Standard Library Modules
Python's standard library includes many useful modules:
math- Mathematical functionsrandom- Random number generationdatetime- Date and time operationsos- Operating system interfacesys- System-specific parametersjson- JSON data handlingre- Regular expressions
Creating Your Own Modules
You can create your own modules by saving Python code in a .py file:
Packages
Packages are directories containing multiple modules. They must have an __init__.py file:
Best Practices
✅ Module Usage Tips
• Use specific imports instead of import *
• Organize related functions into modules
• Use packages for larger projects
• Follow Python naming conventions (lowercase, underscores)
• Document your modules with docstrings