No one will ever need python 2 soon, so check the section about python 3 at the end of the article for the code.
In python, the unit of the code distribution is a module. A module is a simple file with the code. You can find out the name of the module using the global __name__ variable.
When a module is imported, its code is executed. For that reason, there are no limitations on exactly what kind of code it should contain. So, for instance, it can be a collection of functions:
$ cat python_modules/mathematical_functions/powers/base.py
def square(x):
return x * x
def cube(x):
return x * x * x
Modules are grouped into packages. Let's look at the package structure. The code of the main program can be found in program.py, the code of module — in mathematical_functions. The hierarchy looks like this:
$ ls -R python_modules/
python_modules/:
mathematical_functions program.py
python_modules/mathematical_functions:
__init__.py powers
python_modules/mathematical_functions/powers:
base.py __init__.py sums.py
It can be called a package if there is the __init__.py file. If this file is empty, the module can be imported using the import keyword or from-import combination.
$ cat python_modules/program.py
from mathematical_functions.powers import *
print base.square(2)
print base.cube(2)
…
When using from keyword, there is no need to call the imported functions using their full name (including the module name).
Important note about how that … import * works from the listing above. There is no other option except going over the list of all files in the directory of the package and including all the modules one by one. For that reason, it is better to import only required modules, and, for the proper functioning of the … import * statement, it is necessary to list all the modules that can be found in the package in __init__.py.
$ cat python_modules/mathematical_functions/powers/__init__.py
__all__ = ['base', 'sums']
base and sums corresponds to files found in the python_modules/mathematical_functions/powers directory.
For this small section, the code was updated to run against python 3, based on the first version: mathematical-functions-python.
For python 3, the __init__.py file is also important, however, in order to refer to the module in __init__.py, the dot symbol needs to be used — see sums.py file.