The import
keyword in Python is used to access features from modules and packages. In Python, a package is a collection of modules, and a module is a single file containing Python code. When you use the import
statement, you can bring in functions, classes, and variables defined in other modules or packages into your current script or module.
Here are some examples of how import
is used in python.
1). Importing an entire module:
import math
print(math.sqrt(16)) # Accessing the sqrt function from the math module
2). Importing specific attributes from a module:
from math import sqrt, pi
print(sqrt(16)) # Directly using sqrt without the module prefix
print(pi) # Accessing the constant pi directly
3). Importing a module and giving it an alias:
import numpy as np
array = np.array([1, 2, 3, 4])
print(array)
4). Importing a specific function and giving it an alias:
from math import sqrt as square_root
print(square_root(16))
5). Importing all attributes from a module (not recommended due to potential namespace conflicts):
from math import *
print(sqrt(16))
print(pi)
When you import a package, you can also access its submodules or subpackages using the dot notation:
import mypackage.subpackage.module
Or you can use relative imports within a package:
from . import sibling_module
from .subpackage import another_module
Using import
effectively allows you to organize your code into manageable and reusable components.