In Python, the import statement is used to bring in modules and their functionality so you can use them in your code. There are several variations of the import statement, each serving different purposes depending on what and how you want to import.
1. Basic Import
import math
This imports the entire math module. You access its functions with the module name:
math.sqrt(16)
2. Import with Alias
import numpy as np
This imports the module and gives it a shorter alias (np), which is useful for long module names or common conventions.
3. Import Specific Functions or Classes
from math import sqrt, pi
This imports only the specified items from the module. You can use them directly:
sqrt(25)
4. Import All (Not Recommended)
from math import *
This imports everything from the module into the current namespace. It’s discouraged because it can lead to name conflicts and makes code harder to read.
5. Dynamic Import (Using __import__)
module_name = “math”
math_module = __import__(module_name)
This is useful when the module name is determined at runtime.
6. Import from a Package
If you have a package with submodules:
from mypackage import submodule
Or even deeper:
from mypackage.submodule import myfunction
7. Relative Imports (Used in Packages)
from . import sibling_module
from ..parent_package import parent_module
These are used within packages to refer to other modules relative to the current module’s location.
Leave a Reply