← Python lessons

How to Create Your Own Python Module

Any .py file is a module. Save some functions in one file, and you can import them into another file in the same folder.

Read Import first. The first two examples need two files, so try them on your own computer.

Write the module file

Make a file called greetings.py and put your functions in it. The file name without .py is the module name.

# greetings.py
def hello(name):
    return f"Hello, {name}!"

def goodbye(name):
    return f"Bye, {name}."

Import it from another file

Make main.py in the same folder. Import the module by its name, then use its functions.

# main.py
import greetings
from greetings import goodbye

print(greetings.hello("Ada"))
print(goodbye("Ada"))

Run main.py from that folder:

python main.py

It prints Hello, Ada!, then Bye, Ada.. Python finds greetings.py because it sits next to the file you ran. A __pycache__ folder may appear too. It holds a ready-to-load copy of the module, so you can ignore it.

Run code only when the file is run directly

Importing a module runs all of its top-level code. Python sets __name__ in every file: it is "__main__" in the file you run, and the module name, such as "greetings", in a file that is imported.

def hello(name):
    return f"Hello, {name}!"

print("__name__ is", __name__)

if __name__ == "__main__":
    print(hello("test run"))

This page runs the block as the main file, so both lines print. Put test code under if __name__ == "__main__":. It runs when you run the module itself, but not when another file imports it.

Note: Do not name your file after a standard module, such as math.py or random.py. Python would import your file instead, and code that needs the real module would break.

See also: Decomposition, Defining functions.

Your turn

Add an if __name__ == "__main__": block that prints shout("hello").

def shout(text):
    return text.upper() + "!"

# add two lines: only when this file is run directly, print shout("hello")

Expected output

HELLO!

Practise this in the free Python course, where every exercise checks your code instantly.