
PYTHON — Import Statements in Python- A Comprehensive Summary
Simplicity is the soul of efficiency. — Austin Freeman
Import Statements in Python: A Comprehensive Summary
Import statements in Python are used to bring in modules or packages from external libraries or other Python files. This tutorial provides a comprehensive summary of different variations of import statements and their usage.
Variations of the import Statement
There are four variations of the import statement in Python. Let's examine each one with examples:
1. import <module>
When you use import <module>, you import the entire namespace of <module> into the name <module>. The imported module names can be accessed from the calling <module> with <module>.<name>. Here's an example:
import math
print(math.pi) # accessing the constant pi from the math module2. import <module> as <other_name>
With import <module> as <other_name>, you import the entire namespace of <module> into the name <other_name>. This is useful when the module name is long and you wish to import an abbreviated version of it or if the module name clashes with an existing name in the calling module. Example:
import numpy as np
print(np.array([1, 2, 3])) # accessing the array function from the numpy module3. from <module> import <name1>, <name2>
This variation allows you to import only specific names from the module. The names are added to the calling module’s namespace and can be accessed directly. Example:
from datetime import datetime, timedelta
print(datetime.now()) # accessing the now() function directly4. from <module> import <name> as <other_name>
The fourth variation is a combination of the second and third, allowing you to import specific names from a module with an alternative name for each. Example:
from statistics import mean as average
print(average([1, 2, 3, 4, 5])) # accessing the mean function as 'average'Best Practices and Considerations
import <module>is the preferred approach as it keeps the imported module’s namespace completely separate from the calling module’s namespace.import <module> as <other_name>is useful for long module names or to resolve naming clashes.- Importing specific names from a module should be done sparingly, as it removes them from the context of the calling module and can lead to loss of context and readability issues.
It’s important to curate your namespace when importing modules to ensure clarity and maintainability of your code.
In conclusion, understanding the various import statements and their best practices is crucial for writing maintainable and readable Python code.
Feel free to experiment with these import statements in your Python projects to gain a deeper understanding of their usage and benefits.
