🐍 Imports

imports

Good to know

⭐️ Importing lets you reuse code from other files, modules, or libraries. You can import whole modules, specific functions, or entire classes. Imports happen at the top of a file by convention. Note: When you import a module, Python executes that module’s top-level code once, and then caches it.


Importing a Full Module

Imports everything inside the module and accesses it with the module name.

import math
 
print(math.sqrt(16))

Importing Specific Functions or Classes

Avoids having to prefix with the module name.

from math import sqrt
 
print(sqrt(16))

Importing Multiple Items

from math import sqrt, ceil, floor

Importing With an Alias

Useful for shortening long module names.

import numpy as np
 
print(np.array([1, 2, 3]))

This can overwrite names and make debugging harder.

from math import *

Importing Your Own Python Files (Modules)

Any .py file is a module you can import. Ensure both files are in the same folder or Python path.

# file: helpers.py
def greet():
    print("Hello!")
# file: main.py
import helpers
 
helpers.greet()

Importing Classes From Another File

# file: dog.py
class Dog:
    def bark(self):
        print("Woof!")
# file: main.py
from dog import Dog
 
d = Dog()
d.bark()

Importing a Module Inside a Folder (Package)

Folders with an init.py file are considered packages.

project/
β”œβ”€β”€ animals/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── dog.py
└── main.py
# main.py
from animals.dog import Dog

Relative Imports (Inside Packages)

Useful when modules live in the same package.

from .dog import Dog
from ..utils import helper_function

Checking Installed Modules

import sys
print(sys.modules)