Python - Modules

2020-04-25

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
touch index.py

Creating a module

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

# myModule.py

MY_CONSTANT = 5

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 index.py file and add the following:

# index.py

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.

References

GoTea - KoalaTea