How To Make Your Own Library In Python

In this tutorial, we're going to help ourselves by making our very own tool-kit. This tool-kit includes our special functions. When we need to solve something, or execute a specific operation inside our main application, which cannot be supported from current Python libraries, we will import and refer to our own Library. The steps for creating your own library are the following:
  • You need to understand that you don't actually call a LIB file, but a python script. ( So your library is actually a python script.

  • Open Python Shell and hit CTRL + N to create a new python script.

  • Save the python script with the name of your library. e.g

  • This step is IMPORTANT: Make sure that your file is inside the directory of Lib in the Python Folder. When you're saving it, (previous step) just modify the path to this: "C:\Python27\Lib" or this "C:\Python34\Lib". This will store your "library" to the proper location so you can import it later on.

How We Import Our Modules

In order to input our own library/module, once developed, we use this particular syntax.

from OurLibraryName import *

You call the name of your library and you basically say, "Ok, I want access to each of the functions inside that lib". Let's assume that our lib has these functions:

def addition(numOne, numTwo):
    return numOne + numTwo

def multiplication(numOne, numTwo):
    return numOne * numTwo

Open your script and paste these functions EXACTLY the way you see them. Click "Save" and head to the python shell. Let us do a test.

  • Check whether the library works properly or not!
    >>>   from Library import *

    If no Traceback/errors appear means that you successfully imported your library!

  • Now you can call a function from inside the library! Let's add 2 numbers!!
    >>>   addition(45, 5)
    We've used the function "addition" from our library file. Cool huh?

  • If for some reason you want ONLY ONE function from the entire library you'll import it like this!
    >>>   from Library import addition
    #Let's add 2 numbers!
    >>>   addition(3, 6)

    This option will import ONLY the function named addition(). You'll not able to use the rest of the functions on command.

Try it!

This is a part of a library named pySideLib written by a student to help himself with an assignment. However, he doesn't know the process of how to use it properly. Can you help him by pointing out key steps?
def cube(number):
    print "The cube of " + number + " is: \n"
    return number ** 3

def dev(number, rate):
    number = number/43
    rate = int(number) + 4000
    data = []
    return data

def square(number):
    print "The square of " + number + " is: \n"
    return number ** 2

Import the entire library as indicated before:

Import just the cube function from our library as indicated before:

Call function square with parameter the number 4. Assume that we have already imported the entire library.
? | Contact Me | © 2016