Importing Modules
In Python, modules allow you to organize and reuse your code. A module is simply a .py
file that contains functions, classes, or variables that you can use in other programs. Importing modules is a fundamental practice for writing clean, maintainable, and scalable code.
Why Import Modules?
Section titled “Why Import Modules?”- Reuse: Use already written functions and classes, avoiding repeated code.
- Organization: Divide your project into smaller, more manageable files.
- Access to tools: Take advantage of Python’s vast standard library and external packages.
Importing Standard Modules
Section titled “Importing Standard Modules”Python includes a large number of ready-to-use modules. For example, to work with dates you can import the datetime
module:
import datetime
today = datetime.date.today()print('Today's date is:', today)
Importing Specific Functions or Classes
Section titled “Importing Specific Functions or Classes”You can import only what you need from a module:
from math import sqrt
print(sqrt(16)) # 4.0
Renaming Modules Upon Import
Section titled “Renaming Modules Upon Import”Sometimes an alias is used to shorten the module name:
import numpy as np
array = np.array([1, 2, 3])print(array)
Importing Your Own Modules
Section titled “Importing Your Own Modules”If you have a file named utilities.py
in your project, you can import it like this:
import utilities
utilities.my_function()
Best Practices
Section titled “Best Practices”- Import only what you need.
- Use aliases (
as
) for long or common names. - Keep your imports at the beginning of the file.
Summary
Section titled “Summary”- Modules help you organize and reuse code in Python.
- You can import standard, external, or custom modules.
- Use the different forms of import according to your needs.
Ready to test? Try importing the random
module and generate a random number.