Python Tutorial Series – Modules

A Python module is composed of the classes, functions and variables contained in a single python file. A python file can contain multiple classes, not just a single class like in Java. Module names should be simple and ideally kept to one word.

Below is an example module, which is contained in a file called mod.py:
Note: The module name is the name of the file minus the .py extension.


ONE = 1

def do_something():
  print(‘I am a function that does something’)

class Class1:
  def __init__(self, a):
    self.a = a

  def printa(self):
    print(self.a)

Modules are imported as follows:


import mod

This imports mod into the current symbol table, not everything inside mod. Everything inside mod is accessible though.

Modules may also be imported using a shortcut for the module name:


import mod as m

Individual names may be imported into the current symbol table as follows:


from mod import Class1

This does not import mod into the symbol table though, only Class1.

Names may also be imported using:


from mod import *

However, this method is not recommended as it’s introducing unknown names and could override something already defined.

If a module member is frequently used, it can be assigned to a variable to shorten things up as follows:


import mod

do = mod.do_something()
do()

This would also work:


from mod import do_something as do

do()

The example mod module could be used by another file, main.py, as follows:


import mod

mod.do_something()
print(mod.ONE)

clazz = mod.Class1(5)
clazz.printa()

Modules should be well organized and contain classes, functions and variables which make sense being grouped together. I’m not a big fan of super large files. Since there is not a restriction on how many classes can be defined in a single file, a file could get large quickly. If a class, function, or the module itself, is pretty large, it could be a sign there’s too much going on and may be able to be broken down further into smaller pieces.

More Python