Modules and Packages

What are Modules

A module is a file containing Python code (functions, variables, classes) that can be reused in other programs.

Example

If you have a file named math_utils.py, it is a module.

Why Use Modules

  • Code reusability
  • Better organization
  • Easier debugging and maintenance
  • Avoid code duplication

Types of Modules

  • Built-in modules (provided by Python)
  • User-defined modules (created by users)

  • Importing Modules

Python provides multiple ways to import modules.

import Statement

import mathprint(math.sqrt(16))

from ... import Statement

from math import sqrtprint(sqrt(25))

Import with Alias

import math as mprint(m.pi)

Importing Specific Functions

from math import pi, sqrt

dir() Function

Lists all attributes of a module.

import math
print(dir(math))
  • Creating Modules

Writing a Module

Create a file my_module.py:

def greet(name):
return f"Hello {name}"

Using the Module

import my_moduleprint(my_module.greet("Pooja"))

name Variable

if __name__ == "__main__":
print("Running directly")

Explanation

  • When file is run directly → __name__ = "__main__"
  • When imported → __name__ = module name

Module Search Path

Python searches for modules in:

  • Current directory
  • Installed libraries
  • System paths

  • Python Standard Library

The Python Standard Library is a collection of built-in modules that provide ready-to-use functionality.


Commonly Used Modules

math Module

import mathprint(math.sqrt(16))
print(math.factorial(5))

random Module

import randomprint(random.randint(1, 10))
print(random.choice([1, 2, 3]))

datetime Module

import datetimenow = datetime.datetime.now()
print(now)

Benefits

  • Saves development time
  • Provides reliable and tested functions
  • Widely used in real-world applications

  • Introduction to Packages

A package is a collection of modules organized in directories.


Package Structure

my_package/
__init__.py
module1.py
module2.py

init.py File

  • Marks a directory as a package
  • Can contain initialization code

Importing from Packages

from my_package import module1module1.function()

Advantages of Packages

  • Organize large projects
  • Avoid naming conflicts
  • Improve code structure

Conclusion

Modules and packages are essential concepts for organizing Python code efficiently. Modules allow you to reuse code by splitting it into manageable files, while packages help structure large projects into logical groups.

The Python Standard Library provides powerful built-in modules that simplify development and reduce effort. By understanding how to create and use modules and packages, learners can write clean, maintainable, and scalable applications.

Mastering these concepts is a key step toward professional Python development and working on large-scale real-world projects.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *