Python – Modules and Packages Example

Sometimes we want to modularize our code, and group code into modules or packages for reusability & organizational purposes.

# from lib.py

def my_function():
    print("Hello From My Function!")

def my_function_with_args(username, greeting):
    print("Hello, {} , From My Function!, I wish you {}"
        .format(username, greeting))

def sum_two_numbers(a, b):
    return a + b


# from main.py in same folder

import lib

if __name__ == "__main__":
    lib.my_function()

    #prints - "Hello, John Doe, From My Function!, I wish you a great year!"
    lib.my_function_with_args("John Doe", "a great year!")

    # after this line x will hold the value 3!
    x = lib.sum_two_numbers(1,2)
    print(x)

Now, when we run the main function and call “lib.my_function()” for example, it will run my_function() from the lib.py file in the same directory.