Main Content

Method, Class, Module, Package - how to they relate in Python?

Archive - Originally posted on "The Horse's Mouth" - 2015-10-17 19:06:15 - Graham Ellis

A file containing a number of python methods and classes is known as a module. In the simplest of cases, it mighy just contain one class.

A directory containing a number of python modules is known as a package. In the simplest of cases, it may just contain one module.

Here's a sample program that loads a class (or two) from within a module from within a package:

  import bundle.thing
  iHave = bundle.thing.matchbox("catapillar")
  print(iHave)


In Python 2, you are required to mark a package as being a package by having a file called __init__.py in the directory. This was described as being necessary to avoic confusion between module names if your package contained modules of the same name as standard modules. Failure to provide the file results in:

  WomanWithCat:flask grahamellis$ python bundemo
  Traceback (most recent call last):
    File "bundemo", line 2, in <module>
      import bundle.thing
  ImportError: No module named bundle.thing
  WomanWithCat:flask grahamellis$


In Python 3 there is no such requirement for a __init__.py file:

  WomanWithCat:flask grahamellis$ python3 bundemo
  A Matchbox containing catapillar
  WomanWithCat:flask grahamellis$


Although not needed in Python 3, both versions support the file whichc also allows the specificiation of code to be run on load, and allows you to define a __all__ variable which controls what you load when you import or from *.

Files in this demo:
Demo program using package
Python module to go within package