Categories:

Modules and Packages in Python

For the finale of our Python basics (I will still create more Python guides soon), we are going to go over modules and packages. A module, in terms of programming, is a bit of software that has been given functionality. An example of modules, in a realistic application, could be a game such as chess. When you build a chess game, you need a module for the logic of the game and possibly another module for the visuals of the game (realistically, it would be more complicated than this). A module can be edited separately since they are different files.

Writing modules

A module refers to a file that has statements, definitions, and a bunch of other fun stuff. Here is an example: “sample.py,” is a module and the module name would simply be “sample.” We can utilize a module to break down a big program into something smaller that is easier to work with. Modules, in their own right, offer a method of recycling code.

Here is an example of how we can generate a module:

# save file as example.py
# module
def add(x, y):
   result = x + y
   return result

Based on what we got, we have created a function with an “add()” within a module called “example.” This specific function collects two integers and returns the sum of the numbers.

How do we import the module?

All we have to do is simply use this special keyword: import.

import example

This will only import the module named “example” but not the names of the functions that are inside of it. Utilizing the module name, we can access a function by utilizing a dot operator:

example.add(2,3.5) # 5.5

Python has a lot of standard modules you could utilize, and you can check them out here: Python Module Index. There are several ways to import modules, here are some examples:

Python import statement:

import math
print(math.pi) # 3.141592653589793

Import with renaming:

import math as x # we renamed the math module as 'x'
print(x.pi) 

From import statement:

from math import pi
print(pi)

Import all names:

from math import * # asterisk symbol is for importing everything
print(pi)

Module Search Path

When Python is importing a module, several places are examined during the import process. The first thing we look for is a built-in module. Then it will look in a series of directories that are defined in the system (sys.path). The sequence goes as such:

  • Current directory
  • “PYTHONPATH” (environment variable that has a collection of directories)
  • Installation-dependent default directory
import sys
sys.path
['',
'C:\\Python\\Lib\\lib_x',
'C:\\Windows\\system32\\python.zip',
'C:\\Python\\DLLs',
'C:\\Python\\lib',
'C:\\Python',
'C:\\Python\\lib\\site-packages']

Module: Reloaded

For a Python interpreter, it first imports a module only one time during a given session; this enables efficiency. Here is an example:

x_module:

print("some code...")

Multiple imports:

import x_module # executes
import x_module # does not execute
import x_module # does not execute

As you can see, only one of the imports got executed (this implies it was imported just once). Say if there was a modification, then you would have to reload it and you can utilize the “reload()” function.

For example:

import x
import x_module # this gets executed
import x_module
x.reload(x_module) # this gets executed
# <module 'my_module' from '.\\my_module.py'>

Hey, dir()

The last function I want to go over is dir(). This function allows you to find names defined within a module. Here is an example:

dir(x)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']

We can utilize a sorted list of names, based on the above (you can even toss in “add” if you feel the need to do so). Other names that start with an underscore are default attributes that are affiliated with the module and are not defined by the user.

Here is an example:

import x
x.__name__ # x

All of the names that are defined within the current namespace can be discovered by utilizing, as mentioned previously, a “dir()” function (no need for an argument).

x = 1
y = "hi"
import math
dir()
['__builtins__', '__doc__', '__name__', 'x', 'y', 'math']

For more information

If you seek to learn more about Python, please visit Python’s official documentation.