Creating our Own Module

 

Besides importing built-in modules, we can also create our own modules. This is very useful if you have some functions that you want to reuse in other programming projects in future.

 

Creating a module is simple. Simply save the file with a .py extension and put it in the same folder as the Python file that you are going to import it from.

 

Suppose you want to use the checkIfPrime() function defined earlier in another Python script. Here’s how you do it. First save the code above as prime.py on your desktop. prime.py should have the following code.

 

def checkIfPrime (numberToCheck):

for x in range(2, numberToCheck):

      if (numberToCheck%x == 0):

            return False

return True

 

Next, create another Python file and name it useCheckIfPrime.py. Save it on your desktop as well. useCheckIfPrime.py should have the following code.

 

import prime

answer = prime.checkIfPrime(13)

print (answer)

 

Now run useCheckIfPrime.py. You should get the output True. Simple as that.

 

However, suppose you want to store prime.py and useCheckIfPrime.py in different folders. You are going to have to add some codes to useCheckIfPrime.py to tell the Python interpreter where to find the module.

 

Say you created a folder named ‘MyPythonModules’ in your C drive to store prime.py. You need to add the following code to the top of your useCheckIfPrime.py file (before the line import prime).

 

import sys

 

if 'C:\\MyPythonModules' not in sys.path:

sys.path.append('C:\\MyPythonModules')

 

sys.path refers to your Python’s system path. This is the list of directories that Python goes through to search for modules and files. The code above appends the folder ‘C:\MyPythonModules’ to your system path.

 

Now you can put prime.py in C:\MyPythonModules and checkIfPrime.py in any other folder of your choice.