Python Modules

What is module in python ?

In Python, modules are simply files containing Python code. They can define functions, classes, and variables that you can use in other Python scripts by importing them. Modules help in organizing code and making it reusable.

Creating a module in Python

You create a module by writing Python code in a .py file. For example, if you have a file named util.py, it can be considered a Python module.

Save below code in a file named util.py

def greeting(name):
    return f"Hello {name}!!!"

Using a Module

You can import and use the functions, classes, and variables defined in the module.

import util

print(util.greeting("Proedu"))

# Output
Hello Proedu!!!

When you import a module, Python searches for it in the directories listed in the sys.path variable. This includes the directory containing the script you’re running and the built-in modules.

Variables in a Module

In Python modules, variables can be defined just like functions or classes. Here’s how you can define and use variables within a module.

Defining variable in module

You can define variables at the top level of a module. These variables can be simple data types like integers, floats, strings, or more complex data structures like lists, dictionaries, or custom objects.

# Inside file util.py
# Define some variables
count = 42
message = "Hello, Proedu!"
my_list = [1, 2, 3, 4, 5]


def greeting(name):
    return f"Hello {name}!!!"

Accessing variable from a module

After importing the module, you can access these variables using dot notation (module_name.variable_name).

import util

print(util.greeting("Proedu"))
print("Message: ", util.message)
print("Count: ", util.count)
print("List: ", util.my_list)

# Output
Hello Proedu!!!
Message:  Hello, Proedu!
Count:  42
List:  [1, 2, 3, 4, 5]

You can create an alias when you import a module, by using the as keyword
import my_module as util

Changing Variable Values

You can modify the value of variables defined in a module, but it’s essential to understand that if multiple scripts import the same module, they’ll share the same variable.

Create python module util.py

# util.py
count = 42
message = "Hello, Proedu!"
my_list = [1, 2, 3, 4, 5]

Changing variable value in script1.py

import util
print(util.count)
util.count = 100
print(util.count)

#Output
42
100

Accessing variable value in script2.py

import util
print(util.count)

# Output
100 

Variables in modules provide a way to share data between different parts of your program and can be useful for storing constants, configuration settings, or other global data.

Using dir() function

The dir() function in Python is a powerful built-in function that returns a list of valid attributes of the object passed to it. When used without arguments, it returns the list of names in the current local scope.

When used with a module as an argument, dir() provides a list of all the attributes and functions defined in that module. Here’s how you can use dir() with modules:

import sys
module_list = dir(sys)
for module in module_list:
    print(module)

# Output
__displayhook__
__doc__
__excepthook__
activate_stack_trampoline
addaudithook
api_version
argv
...

This will print a list of all attributes, functions, classes, and variables defined in the sys module.

However, it’s worth noting that dir() will also return some attributes that are built-in to all modules, like __name__, __doc__, __file__, and so on. These attributes provide information about the module itself.

Packaging multiple modules

Packaging multiple modules in Python involves organizing related modules and sub-packages into a directory structure and providing an __init__.py file in each directory to mark it as a package.

Here’s a step-by-step guide on how to package multiple modules in Python.

  • Organize your modules
  • Create __init__.py files
  • Write your modules
  • importing modules within the package
  • Using the package
  • Distributing the package

Organize your module

Decide on a directory structure for your package. Typically, you’ll have a main package directory containing subdirectories for different parts of your package, each representing a module or a sub-package.

my_package/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
    ├── __init__.py
    ├── submodule1.py
    └── submodule2.py

Create __init__.py Files

  1. In each directory of your package, create an __init__.py file. This file can be empty or contain initialization code for the package or module. These files are necessary to make Python treat the directories as containing packages or sub-packages.

    Write Your Modules

Write your Python modules and sub-modules as separate .py files within the package directory structure. Each module should contain functions, classes, or variables that are related to each other.

Importing Modules within the Package

When importing modules or sub-packages within the same package, you can use relative imports. For example, to import module1.py from module2.py within the same package, you can use

from . import module1

Here, the dot (.) signifies that you’re importing relative to the current package.

Using the Package

Once you’ve created your package, you can use it in your Python scripts by importing it like any other module.

import my_package
my_package.module1.some_function()

Distributing Your Package

If you want to distribute your package so that others can install and use it, you can create a setup.py file and use tools like setuptools or distutils to package and distribute your code. This involves providing metadata about your package, such as its name, version, and dependencies.

    Packaging your modules allows you to organize your code into reusable components and easily share them with others. It also helps in maintaining a clean and structured codebase.

    Leave a Reply