Python Modules: Organizing Code with Libraries and Functions

Explore Python modules, which function as code libraries to organize and manage your code effectively. Discover how modules can contain functions, classes, and resources to streamline your application development and enhance code readability.



Python Modules

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

If your program involves defining numerous functions and classes, organizing them into modules can be very effective. Each module can store classes, functions, and other related resources, making your code more manageable and easier to understand.

Creating a Module

Here is a Python script defining a sum() function, saved as calc.py.

Example

# calc.py
def sum(x, y):
    return x + y
        

Importing a Module

You can now import this module and execute the sum() function in the Python shell.

Example

import calc 
result = calc.sum(8, 7) 
print(result)
        
Output

15
        

You can use the same approach to import the calc module in another Python script using the import statement. All modules, whether built-in or custom, are objects of the module class. You can verify this using the type() function.

Example

import calc
print(type(calc))  # <class 'module'>

import math
print(type(math))  # <class 'module'>
        
Output

<class 'module'>
<class 'module'>
        

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Renaming the Imported Module

You can use the as keyword to rename the imported module.

Example

import math as m
result = m.sqrt(25) 
print(result)
        
Output

5.0
        

Variables in Modules

A module can include not only functions but also variables of various types such as arrays, dictionaries, objects, etc.

Example

Save the following code in a file named mymodule.py:

Example

# mymodule.py
person1 = {
  "name": "Alice",
  "age": 30,
  "country": "USA"
}
        

Importing the Module

Import the module named mymodule and access the person1 dictionary:

Example

import mymodule

age = mymodule.person1["age"]
print(age)
        
Output

30
        

Built-in Modules

Python includes several built-in modules which you can import at any time.

Example

import platform

system = platform.system()
print(system)
        
Output

Linux
        

Using the dir() Function

The dir() function lists all the function names (or variable names) in a module.

Example

import platform

names = dir(platform)
print(names)
        
Output

['_Processor', '_UNIXCONFDIR', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_default_architecture', '_default_ver', '_follow_symlinks', '_is_x86', '_node', '_platform', '_release', '_sys_version', '_syscmd_uname', '_syscmd_ver', '_sys_version', '_uname_cache', '_uname_result', '_ver_stages', 'architecture', 'collections', 'dist', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os', 'platform', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'sys', 'system', 'system_alias', 'uname', 'version', 'win32_ver']
        

The dir() function can be used on any module, including user-defined ones.

Importing Specific Parts of a Module

You can import only certain parts of a module using the from keyword.

Example

# mymodule.py
def greeting(name):
  print("Hello, " + name)

person1 = {
  "name": "Alice",
  "age": 30,
  "country": "USA"
}
        

To import only the person1 dictionary from the module:

Example

from mymodule import person1

print(person1["age"])
        
Output

30
        

Note: When using the from keyword, do not use the module name when referring to elements from the module. For example, use person1["age"] instead of mymodule.person1["age"].

Using the from...import Statement

You can use the from...import statement to load all resources of a module into the current namespace or to import specific objects from a module. For instance, the following module calc.py has three functions.

Example

# calc.py
def sum(x, y):
    return x + y

def average(x, y):
    return (x + y) / 2

def power(x, y):
    return x ** y
        

To import specific functions from this module, you can use the following syntax.

Example

from calc import sum, average
n = sum(12, 8)  # 20
avg = average(12, 8)  # 10
        
Output

20
10
        

You can also import all functions from a module using the from...import * syntax.

Example

from calc import *

n = sum(12, 8)
print(n)

avg = average(12, 8)
print(avg)

p = power(2, 3)
print(p)
        
Output

20
10
8
        

Module Search Path

When an import statement is encountered, the Python interpreter searches for the module in the following locations:

  1. Current working directory
  2. Directories in the PYTHONPATH environment variable
  3. Installation default directory

These locations are listed in the sys.path attribute.

Example

import sys
print(sys.path)
        
Output

['', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', 
'/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages']
        

If the required module is not found, a ModuleNotFoundError is raised.

Example

import unknownmodule
        
Output

Traceback (most recent call last):
  File "", line 1, in 
ModuleNotFoundError: No module named 'unknownmodule'
        

Reloading a Module

If a module is modified after being imported, you can reload it using the reload() function from the imp module to get the latest version.

Example

import imp
import calc
imp.reload(calc)
        

Getting Help on Modules

Use the help() function to learn about the methods and properties of a module. For example, call help("math") to get information on the math module. If the module is already imported, simply provide its name, such as help(math).

Alternatively, the dir() function can be used to list the names and attributes of a module.