Python - Modules


Python modules are separate files that allow you to organize your code. You can add variables, functions, class and more to a module. Let's take a look at a simple example.

Setup the project

Let's start with a basic project setup.

mkdir moduleExample

Creating a module

Start by creating a new file called Inside the file, add the following:



def doComplexMath(a, b):
    return a ** b # Raises a to the power of b

Using the module

Alright, now that we have a custom module, let's use it. Open up the file and add the following:


import myModule

print(myModule.MY_CONSTANT) # prints 5
print(myModule.doComplexMath(2, 8) # prints 9

There you go! Now, you can organize your code into nice small modules.