π 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, floorImporting With an Alias
Useful for shortening long module names.
import numpy as np
print(np.array([1, 2, 3]))Importing Everything (Not Recommended)
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 DogRelative Imports (Inside Packages)
Useful when modules live in the same package.
from .dog import Dog
from ..utils import helper_functionChecking Installed Modules
import sys
print(sys.modules)