Creating and Importing Custom Python Modules: Splitting Code into Multiple Files

As a Python program grows in size, managing all the code in a single file (.py) becomes difficult. In such cases, it is common practice to split functions and classes into separate files based on their functionality and load (import) them as needed. These individual files are called “Modules.”

This article explains the basic steps to create a custom module and use it from another script.


目次

1. Creating a Module (Definition Side)

Creating a module is very simple. You just need to create a file with the .py extension and write functions or variables in it.

As an example, let’s create a module named math_utils.py that provides calculation functions.

File Name: math_utils.py

# Module variables
APP_NAME = "Simple Calculator"
DEFAULT_TAX_RATE = 0.1

def add(x, y):
    """Function to add two numbers"""
    print(f"[math_utils] add function called: {x} + {y}")
    return x + y

def subtract(x, y):
    """Function to subtract two numbers"""
    return x - y

Now, a module named math_utils is defined.


2. Using the Module (Caller Side)

To use the created module, place the script you want to use (here called main.py) in the same directory (folder) as the module file, and use the import statement.

File Name: main.py

# Import the created math_utils module
# (The .py extension is not needed)
import math_utils

print("--- Process Start ---")

# 1. Using functions inside the module
# Access via module_name.function_name
result_add = math_utils.add(10, 20)
print(f"Addition Result: {result_add}")

result_sub = math_utils.subtract(50, 30)
print(f"Subtraction Result: {result_sub}")

# 2. Using variables inside the module
# Access via module_name.variable_name
print(f"App Name: {math_utils.APP_NAME}")
print(f"Default Tax Rate: {math_utils.DEFAULT_TAX_RATE}")

How to Run: Run main.py in your terminal.

python main.py

Output:

--- Process Start ---
[math_utils] add function called: 10 + 20
Addition Result: 30
Subtraction Result: 20
App Name: Simple Calculator
Default Tax Rate: 0.1

As shown, by writing import module_name, you can access functions and variables defined in that file by adding the prefix module_name..

Importing Specific Features (from ... import ...)

If you want to use only specific functions or variables instead of the entire module, using from is convenient. In this case, you can use the names directly without a prefix.

File Name: main_from.py

# Import only the add function and APP_NAME variable from math_utils
from math_utils import add, APP_NAME

print(f"App: {APP_NAME}")

# Can be called directly without 'math_utils.'
result = add(5, 5)
print(f"Result: {result}")

Important Convention: if __name__ == "__main__":

Sometimes you want to write code inside the module file (math_utils.py) to test if it works. However, if you write it directly, that code will run just by importing the module. To prevent this, it is an important Python convention to use the following if statement.

Modified math_utils.py

# ... (Variable and function definitions are the same) ...

def add(x, y):
    return x + y

# Block executed ONLY when this file is run directly
if __name__ == "__main__":
    print("--- Debug run of math_utils ---")
    print(add(1, 1))
  • When running python math_utils.py directly: The content of the if block is executed.
  • When imported via import math_utils: The content of the if block is not executed (only function definitions are loaded).

Summary

  • Create: Create a .py file containing functions and variables.
  • Import: Write import filename (without extension) in the calling script.
  • Use: Access via module_name.function_name().
  • Test Code: Write inside the if __name__ == "__main__": block to prevent unintended execution during import.

Splitting files makes code easier to read and increases reusability.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次