Home
About Us Privacy Policy
 

MODULES IN PYTHON

ADVERTISEMENT

Advanced Modules



What are modules in Python, and why are they used?

In the Python programming language, modules are a set of statements that are logically related to each other. It can also be conceptualized as a library. It can be daunting at first, but let me explain using a real-world easy to understand example.

We've all been to school and attend different classes and take notes. You could theoretically take all the notes in one notebook for the sake of simplicity, but making the notes very difficult to understand at a later stage and extremely difficult to find content on a particular topic.

What if you could write notes for every topic separately? Wouldn't that make your task easier for organizing and searching for topics efficient? It would. If you want to go through a specific topic in Physics, you have to open the Physics notebook, go to the relevant chapter, and search for it instead of going through your all-on-one notebook.

Modules in Python work the same way as your notebook. They separate programming statements that do a specific thing separately for manageability and organization.

Modules help the programmer organize and manage the codebase.


Advantages of Modules

These are the advantages of Modules:

  • Easy code organization
  • Easy to maintain
  • Code access


ADVERTISEMENT

Creating a Module

In Python, a module is nothing but a Python file itself containing Python statements. However, they must end with the extension py  to be recognized by the Python interpreter as a module.

Save the following code in a Python module named: say_hello.py

# Module: say_hello.py
def greet():
    print("Hello, World!")


Loading a Module

To load a module, Python provides the import keyword.

import say_hello
say_hello.greet()

Let's break down the above statements.

import say_hello

This statement informs Python to look into the current directory and search for the module say_hello. If found, then import it, else generate an exception.

If the module is not found, ModuleNotFoundError will be generated.

say_hello.greet()

This statement informs Python to execute the method greet in the module say_hello. The dot(.) operator is used to access identifiers inside a package.


Loading variables from a module

Python allows for the loading of individual variables from a module, just like functions and classes. The below example demonstrates this feature.

Save the following code in a module called config.py

configurations = {
    "shared_dir": "/home/ajax/shared",
    "temp_dir": "/tmp",
    "access": "rwx"
}
log_file_name = 'log.txt'
username = 'john_doe'

Now create another module named main.py in the same directory.

import config
print(config.configurations["shared_dir"])

/home/ajax/shared


ADVERTISEMENT

Importing only specific identifiers

Unlike other programming languages, Python allows for importing only the required identifiers.

Identifiers could be variables, functions, classes.

Below is the syntax:

from module_name import <module name or *>

To import everything from the module, use the following syntax:

from module_name import *

from config import *
print(configurations["temp_dir"])

To import only required identifiers use the following syntax:

from config import log_file_name, username
print(f"The log file name is {log_file_name}, and the username is {username}")

If you may have noticed, we have omitted the dot(.) notation. Python has made all the identifiers available for use, and hence, they need not be accessed using the dot(.) operator.


Renaming Identifiers

A high-level programming language like Python allows for renaming identifiers to make the code easier to understand and manage.

Before we begin, create two modules, my_network and my_file system, and save the following code.

In the module my_network, save the following code:

# MODULE: my_network
def init():
    print("init() from my_network ")

In the module my_file_system, save the following code:

# MODULE: my_file_system
def init():
    print("init() from my_file_system ")

Suppose you have two modules, my_network, and my_file_system. They both need to be initialized before use and hence, provide the init() method. Here is how that would be written:

import my_network 
import my_file_system

my_network.init()                 # init() from my_network
my_file_system.init()       # init() from my_file_system

But accessing the method using the module name would lead to verbosity and make the code harder to read.

So you decide to import all the methods from both modules like so:

from my_network import *
from my_file_system import *
init()

Upon executing this code, the output is init() from my_file_system . As you can observe, the init() method from my_network did not execute at all. The reason is that the init() method from my_network was redefined with the init() from my_file_system.

To avoid such issues, Python provides the ability to rename identifiers.

Syntax:

from module_name import identifier as alias[, *]

from my_network import init as network_init, *
from my_file_system import as file_system_init, *
network_init()
file_system_init()

The ,* informs Python to load the rest of the modules as they are.

init() from my_network

init() from my_file_system


ADVERTISEMENT

Renaming Modules

Like you can rename identifiers in Python, you can rename modules as well.

Syntax

import module_name as alias

import my_network as mynet
import my_file_system as myfs

mynet.init()
myfs.init()


Conclusion

Modules in Python allow for easy organization and management of codebases and allow for writing maintainable programs easier.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.