Import Statements


15 min.   |   Advanced  

import a Module

Import the whole module and access functions or classes with dot notation.

from ... import ...

Import specific parts (functions, classes, variables) from a module directly.

Aliasing with as

Use as to give a module or function an alias—useful for shortening long names.

Wildcard Import (*)

Import everything from a module (not recommended in most cases).

Avoid using * in production code—it can pollute your namespace and create conflicts.

Importing Custom Modules

You can also import your own .py files as modules.

Suppose you have a file myutils.py with the following code:

|_ myutils.py <- here
def greet():
    print("Hello from myutils!")

You can import and use it on a different Python file:

|- myutils.py
|_ python-advanced.py <- here
from myutils import greet
greet()  # Hello from myutils!
Hello from myutils!

Conditional Imports

You can import modules inside functions or conditionally.

Import Statements: Exercises

Tip Import Statements: Exercise 1

Use the math module to compute the factorial of 15! using the factorial function.

Tip Import Statements: Exercise 2

Use the Counter() function from collections to count occurrences in a data list.

Tip Import Statements: Exercise 3

Use the random library to generate 5 random integers between 1 and 10 using the function randint().

Tip Import Statements: Exercise 4

Compute the dot product between a matrix and a vector using numpy with the function dot().

A\mathbf{x} = \mathbf{b}

Tip Import Statements: Exercise 5

Using pandas package find the mean of column “A” using the method mean() of the data DataFrame object.