9.2 The import Statements

9.2 The import Statements

Learning the various ways to import modules and their elements (import, from...import, as) and the best practices for clean code.

The `import` statement is the mechanism that allows you to make code from one module available in another. There are several ways to do this, each with its own advantages and use cases.

`import module_name`

This is the simplest and recommended way. It imports the entire module and creates a module object in the current namespace. To access functions or variables within the module, you must use the module name as a prefix, followed by a dot (dot notation), e.g., `math.sqrt()`. This approach avoids name conflicts and makes it clear where each function comes from.
import math
print(f"Square root of 16: {math.sqrt(16)}")

`import module_name as alias`

This variation imports the entire module but gives it an alias. It is particularly useful for modules with long names or for maintaining compatibility with established community conventions (e.g., `import numpy as np`, `import pandas as pd`).
import random as rd
print(f"Random number: {rd.randint(1, 10)}")

`from module_name import item`

This syntax imports a specific item (a function, class, or variable) from the module directly into the current namespace. This allows you to use the item without the module prefix (e.g., `pi` instead of `math.pi`). You can import multiple items by separating them with commas. Use it with caution, as it can lead to name conflicts if you import something with the same name you are already using.
from math import pi, pow
print(f"Pi: {pi}, 2^3: {pow(2, 3)}")

`from module_name import *` (Wildcard Import)

NOT RECOMMENDED: This syntax imports all names from a module into the current namespace. Although it may seem convenient, it makes the code very difficult to read and maintain, as it is not at all clear which names come from the module and which are defined locally. It can easily cause name conflicts and should generally be avoided, except in very specific cases (such as in some scientific frameworks or for interactive use in the terminal).

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.