Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
Python - Variable declarations
Conditional Statements in Python
Loops in Python
Python Functions
Python Classes
OOPS in Python
Python - Hello World Application
Python - import statements
Python - Web API

Python - import statements



Import statements in Python allow you to bring in modules and their functions, classes, and variables into your current script or interactive session. This is an essential feature as it promotes code reuse and modularity. Here' a detailed explanation of different ways to use import statements in Python:

Basic Import

The simplest way to import a module is using the import keyword followed by the module name.

python
import math

print(math.sqrt(16))  # Output: 4.0

Import with Alias

You can use an alias to shorten the module name using the as keyword.

python
import numpy as np

array = np.array([1, 2, 3])
print(array)  # Output: [1 2 3]

Import Specific Functions or Classes

If you only need specific functions or classes from a module, you can import them directly.

python
from datetime import datetime, timedelta

now = datetime.now()
print(now)
delta = timedelta(days=5)
print(now + delta)

Import All Contents

You can import all contents of a module using the * wildcard. This is generally not recommended due to potential namespace conflicts.

python
from math import *

print(sqrt(16))  # Output: 4.0

Import from a Subpackage

If you are working with a package that has subpackages or submodules, you can import from them using dot notation.

python
from mypackage.mysubpackage import mymodule

mymodule.myfunction()

Importing Custom Modules

You can also import custom modules you have created. Ensure the module is in the same directory or in a directory included in the Python path.

python
# File: mymodule.py
def greet(name):
    return f"Hello, {name}!"

# File: main.py
import mymodule

print(mymodule.greet("Alice"))  # Output: Hello, Alice!

Using importlib for Dynamic Imports

For dynamic imports, you can use the importlib module to import a module during runtime.

python
import importlib

module_name = 'math'
math_module = importlib.import_module(module_name)

print(math_module.sqrt(16))  # Output: 4.0

Summary

  • import module_name: Imports the entire module.

  • import module_name as alias: Imports the module with an alias.

  • from module_name import function_name: Imports specific functions or classes.

  • from module_name import *: Imports everything from the module (not recommended).

  • importlib.import_module(module_name): Dynamically imports a module.

By using import statements, you can enhance the functionality of your Python programs by leveraging existing modules and creating modular, reusable code. If you have any specific questions or need further examples, feel free to ask!




All rights reserved | Privacy Policy | Sitemap