MyInternships.in

Python Modules & Packages

Python Modules

A module is simply a .py file full of code — functions, variables, classes — that you can reuse in another program with the import keyword.


What Is a Module?

As your programs grow, you cannot keep every function and variable in one file. Python lets you split code into separate files called modules. Any Python file, say math_helpers.py, is automatically a module you can import elsewhere by its filename (without the .py).

Importing a Module

The import statement loads a module and gives you access to everything inside it through dot notation. Built-in modules like math and random ship with Python itself, so you never install them separately.

Basic import
Python
import math

print(math.sqrt(16))
print(math.pi)

from ... import — Bringing In Specific Names

If you only need one or two functions from a module, from-import lets you use them directly, without the module prefix. This keeps your code shorter but be careful of naming clashes with your own variables.

from-import
Python
from math import sqrt, pi

print(sqrt(25))
print(pi)

Renaming With as

The as keyword creates an alias — a shorter or clearer name for a module or function. This is extremely common with popular data-science libraries like pandas and numpy.

Aliasing a module
Python
import math as m
from random import randint as ri

print(m.floor(4.7))
print(ri(1, 10))

Creating Your Own Module

Save any Python file, for example greetings.py, containing functions or variables. In another file in the same folder, import it by its filename and call its contents.

greetings.py
Python
def say_hello(name):
    return f"Hello, {name}!"
main.py
Python
import greetings

print(greetings.say_hello("Riya"))

Exploring a Module With dir()

The built-in dir() function lists every name defined inside a module — handy when you forget an exact function name or want to discover what a library offers.

Listing module contents
Python
import math
print(dir(math))
💡

Keep related functions and classes together in one module so your project stays organised as it grows — this is the first step toward building packages.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships