Create Your First Python Module

Learn how to create a Python module by writing a .py file, adding functions to it, and importing it from another file in the same project.

5 min read

Creating a Python module is one of the simplest things you can do in the language, and that simplicity is deliberate. When you create a Python module, you start with an ordinary file ending in .py that you write with any text editor. You give the file a descriptive name, write some functions or classes inside it, save it, and then import it from another Python file. There is no module declaration keyword, no registration manifest, and no build step. The file exists, therefore the module exists, and the Python import system handles the rest.

Before you create your first module, you should understand what kind of code belongs in one. A module works best when it collects functions, classes, and constants that share a clear purpose. A module named validation.py should contain functions that validate different kinds of input: email addresses, phone numbers, dates. A module named file_helpers.py should contain functions that read, write, copy, and organize files. If you have been working through the earlier section on Python functions and now have a set of related functions that you want to reuse across multiple scripts, those functions are the perfect candidates for extraction into a module. The rule of thumb is cohesion: everything in the module should change for the same reason.

Create the module file and add functions

Start by creating a new .py file in the same directory as your main script. The filename must be a valid Python identifier: it can contain lowercase letters, digits, and underscores, but it cannot start with a digit and it cannot contain hyphens, spaces, or special characters. The convention is to use short, all-lowercase names with underscores between words.

For this example, create a file called greetings.py with three simple functions. Each function takes a name as input and returns a formatted greeting string. There is nothing else in the file: no print statements, no code that runs automatically, just three function definitions that are ready to be imported and called from anywhere.

pythonpython
def say_hello(name):
    return f"Hello, {name}!"
 
def say_goodbye(name):
    return f"Goodbye, {name}!"
 
def greet_many(*names):
    return [say_hello(name) for name in names]

This file is now a complete, importable Python module. The three functions are module-level definitions, which means they become attributes of the module object when the module is imported. The file contains nothing but function definitions, which is exactly what you want for a utility module: no side effects at import time and no code that runs automatically when someone imports it.

Import the module from another file

Create a second file in the same directory, perhaps called main.py, and write an import statement that loads the greetings module. The import statement tells Python to find greetings.py, execute its function definitions, and make the module available under the name greetings in the importing file's namespace. You then access each function through the module prefix, which tells anyone reading the code exactly where the function comes from.

pythonpython
import greetings
 
message = greetings.say_hello("Maya")
print(message)
 
all_greetings = greetings.greet_many("Alex", "Jordan", "Casey")
for g in all_greetings:
    print(g)

Run main.py from the terminal. You should see the greetings printed in order. If you see an ImportError saying the module is not found, check that both files are in the same directory and that greetings.py does not have a typo in the filename. Python's import error messages are usually precise: if it says the module is not found, the file is either missing, misspelled, or in a directory that Python is not searching.

Add the script-mode guard

A module that is only meant to be imported should not contain top-level code that runs immediately. But you might want to include a small demonstration or self-test that runs when you execute the file directly for testing purposes. The standard way to do this is with the name-main guard pattern, which checks whether the file is being run as a script or imported as a module. When you run the file directly, the guarded block executes. When you import it from another file, the guarded block is skipped and only the function definitions are loaded.

This dual-use pattern is used by almost every reusable Python module in the standard library and in third-party packages. It lets a single file serve two purposes without either one interfering with the other. For an in-depth explanation of how this mechanism works and how it interacts with the broader Python runtime, see the article on the Python main module.

Test the module in the interactive interpreter

After creating a module, you can test it interactively by opening a Python interpreter in the same directory. Type the import statement and call the functions to verify they work as expected. You can also use the dir function to inspect every attribute of the module object, which is a quick way to confirm that your function names are available and that no unexpected names have leaked into the module's namespace.

This interactive workflow is one of the reasons Python's module system is beginner-friendly. You do not need to restart a server, recompile anything, or run a build tool. You edit the .py file, restart the interpreter or reload the module, and test again. The feedback loop is short, which encourages experimentation and makes it easy to iterate on your module's design.

Common mistakes and how to avoid them

One frequent mistake is naming a module after a standard library module. If you create a file called math.py, your import statement will find your file instead of Python's built-in math module. Your code will break in confusing ways because your math.py almost certainly does not provide the same functions as the standard library. Check the Python documentation for a list of standard library module names before naming your own modules, and avoid any name that appears in that list.

Another common issue is putting code with side effects at the module level. If greetings.py contains a print statement outside any function, that line runs every time the module is imported. In a large project where many modules import greetings, the console fills with repeated messages that do not help anyone debug anything. Keep module-level code limited to function definitions, class definitions, constant assignments, and import statements. Any code that produces output, modifies files, or connects to a network should live inside a function and be called explicitly.

A third mistake is creating modules that are too large or too small. A module with two thousand lines is hard to navigate and should be split. A module with a single three-line function is probably not worth its own file and should live inside a larger utility module until the collection justifies a dedicated file. If you are comfortable with organizing Python functions across files, the same principles apply to module design. As your collection grows, you will eventually graduate from flat modules to packages, which is covered in the article on creating and using Python packages.

Rune AI

Rune AI

Key Insights

  • Any .py file is a valid Python module with no special registration or configuration required.
  • The module name is the filename without the .py extension, and it must follow Python identifier rules.
  • To use your module, place it in the same directory as the importing script.
  • The if name == 'main' guard pattern lets a file work as both a module and a standalone script.
  • Start by extracting 3 to 5 related functions into a module rather than trying to plan the perfect structure upfront.
RunePowered by Rune AI

Frequently Asked Questions

Can I create a module without any special tools or configuration?

Yes. Any .py file is automatically a module. You do not need to install anything, configure a build system, or register the module anywhere. Just create a .py file, write some functions in it, and import it from another .py file in the same directory. This is one of the simplest features of Python and requires zero setup beyond having Python installed.

Does the module filename have to follow specific naming rules?

Module names must be valid Python identifiers, which means they can contain letters, digits, and underscores but cannot start with a digit. They are also case-sensitive. Avoid naming your module the same as a standard library module like math.py or random.py, because your module will shadow the built-in one and cause confusing import errors.

What happens if I change a module after importing it?

Python caches imported modules, so simply editing the .py file after import does not reload it in a running program. During development, you need to restart your Python interpreter or use importlib.reload to pick up changes. This caching avoids redundant file reads and ensures that module-level code runs exactly once per interpreter session.

Conclusion

Creating a Python module is as simple as saving a .py file with functions or classes inside it. The filename becomes the module name, and you import it the same way you import standard library modules. Start by extracting a few related functions into a module, then let the module grow as you add more utilities that serve the same purpose.