In Python, there are several ways to import modules and their functions. Here are some common import methods:
-
Standard Import:
Import the entire module.import module_nameExample:
import math print(math.sqrt(16)) # Output: 4.0 -
Import Specific Functions or Classes:
Import specific functions or classes from a module.from module_name import function_nameExample:
from math import sqrt print(sqrt(16)) # Output: 4.0 -
Import with an Alias:
Import a module and give it a shorter alias.import module_name as aliasExample:
import numpy as np array = np.array([1, 2, 3]) print(array) # Output: [1 2 3] -
Import All Functions from a Module:
Import all functions and classes from a module (not recommended due to potential naming conflicts).from module_name import *Example:
from math import * print(sin(0)) # Output: 0.0 -
Conditional Imports:
Import modules conditionally, based on certain conditions.if condition: import module_name -
Dynamic Imports:
Import modules dynamically using theimportlibmodule.import importlib module_name = importlib.import_module('module_name')Example:
import importlib math = importlib.import_module('math') print(math.factorial(5)) # Output: 120
These methods provide flexibility in how you structure your imports based on your needs.
