Importing Custom Modules Locally

🏷️ Modules and Imports / Creating Your Own Module

As you start writing more Python scripts, you will naturally want to reuse useful functions across multiple projects. Instead of copying and pasting the same code everywhere, you can create your own custom moduleβ€”a simple Python file containing functions and variablesβ€”and import it locally into your scripts. This keeps your code organized, maintainable, and much easier to debug.


βš™οΈ What Is a Custom Module?

A custom module is just a Python file (with a .py extension) that contains definitions like functions, classes, or variables. You create it once and then import it into any other script that needs its functionality.

  • Any .py file you write can act as a module.
  • The module's name is the filename without the .py extension.
  • You can place your module in the same folder as your main script for simple local imports.

πŸ› οΈ How to Create and Import a Local Module

Step 1: Create your module file

Create a new file named my_helpers.py in the same directory as your main script. Inside it, define a simple function:

  • my_helpers.py contains: a function called greet(name) that returns a greeting string, and a variable called pi set to 3.14159.

Step 2: Import and use the module in your main script

In your main script (for example, main.py), you import the module using the import statement:

  • Write import my_helpers at the top of your script.
  • To call the function, use my_helpers.greet("Alice").
  • To access the variable, use my_helpers.pi.

Expected output when you run main.py:

  • my_helpers.greet("Alice") returns: Hello, Alice! Welcome to Python.
  • my_helpers.pi returns: 3.14159

πŸ“Š Importing Specific Parts of a Module

If you only need one function or variable from your module, you can import it directly using the from ... import ... syntax. This saves you from typing the module name every time.

  • from my_helpers import greet lets you call greet("Bob") directly without the my_helpers. prefix.
  • from my_helpers import pi lets you use pi directly.

Important note: If you import multiple items, separate them with commas: from my_helpers import greet, pi


πŸ•΅οΈ Understanding the Module Search Path

When you write import my_helpers, Python looks for the file in a specific order:

  • First, it checks the current directory (where your main script is running).
  • Then, it checks directories listed in the PYTHONPATH environment variable.
  • Finally, it checks the default installation paths for third-party libraries.

For local custom modules, simply keeping your module file in the same folder as your main script is the easiest and most reliable approach.


πŸ“‹ Comparison: Full Module Import vs. Specific Import

Aspect Full Module Import (import module) Specific Import (from module import item)
Syntax when using You must prefix with module_name. You use the item directly by name
Readability Very clear where the function comes from Less explicit, but cleaner for frequent use
Namespace pollution No risk of name conflicts Can overwrite existing names if you are not careful
Best use case When using many items from the module When using only one or two items frequently

πŸ§ͺ Practical Example: Organizing Utility Functions

Imagine you have several utility functions you use oftenβ€”like converting units or formatting dates. Instead of rewriting them, create a module called utils.py:

  • utils.py contains: celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f).

In your main script, you import it:

  • import utils
  • Call utils.celsius_to_fahrenheit(100) to get 212.0.
  • Call utils.fahrenheit_to_celsius(212) to get 100.0.

This keeps your main script clean and your reusable logic in one place.


⚠️ Common Pitfalls to Avoid

  • Naming conflicts: Do not name your module the same as a built-in Python module (like math.py or sys.py). This will override the standard library and cause unexpected errors.
  • Circular imports: If module A imports module B, and module B imports module A, you will get an error. Keep your imports flowing in one direction.
  • File location: If your module is not in the same folder, Python will not find it. Either move it to the same directory or adjust the PYTHONPATH.

βœ… Summary

Creating and importing custom modules locally is a fundamental skill that helps you write cleaner, more reusable code. You simply:

  1. Write your functions and variables in a .py file.
  2. Place that file in the same folder as your main script.
  3. Use import module_name or from module_name import item to bring its functionality into your script.

This approach saves time, reduces errors, and makes your projects much easier to maintain as they grow.


This is how you import a Python file you wrote yourself from the same folder or a nearby folder.


πŸ”§ Example 1: Importing a module from the same folder

Create a file called tools.py in your project folder, then import it in another script.

# tools.py
def add(a, b):
    return a + b

def greet(name):
    return f"Hello, {name}"
# main.py (same folder as tools.py)
import tools

result = tools.add(5, 3)
print(result)

πŸ“€ Output: 8


πŸ”§ Example 2: Importing only a specific function from your module

Use from to bring in just the function you need, so you don't have to write the module name each time.

# tools.py (same as before)
def multiply(a, b):
    return a * b

def subtract(a, b):
    return a - b
# main.py
from tools import multiply

result = multiply(4, 6)
print(result)

πŸ“€ Output: 24


πŸ”§ Example 3: Importing a module from a subfolder

Place your custom module inside a subfolder named helpers, then use dot notation to import it.

# helpers/calculations.py
def square(x):
    return x * x

def cube(x):
    return x * x * x
# main.py (in the parent folder)
import helpers.calculations

value = helpers.calculations.square(5)
print(value)

πŸ“€ Output: 25


πŸ”§ Example 4: Using an alias for a long module path

Shorten the module name with as when the path is long or you want a cleaner name.

# helpers/calculations.py (same as above)
def double(x):
    return x * 2
# main.py
import helpers.calculations as calc

result = calc.double(9)
print(result)

πŸ“€ Output: 18


πŸ”§ Example 5: Importing all functions from a custom module

Use from module import * to bring every public function into your namespace (use sparingly).

# helpers/strings.py
def upper_case(text):
    return text.upper()

def lower_case(text):
    return text.lower()
# main.py
from helpers.strings import *

greeting = upper_case("hello world")
print(greeting)

πŸ“€ Output: HELLO WORLD


Comparison Table

Technique Syntax When to Use
Full module import import module_name You need multiple functions from the module
Specific function import from module_name import func You only need one or two functions
Subfolder import import folder.module_name Your module is inside a subfolder
Alias import import folder.module as alias You want a shorter name in your code
Wildcard import from module import * Quick prototyping (avoid in larger projects)

As you start writing more Python scripts, you will naturally want to reuse useful functions across multiple projects. Instead of copying and pasting the same code everywhere, you can create your own custom moduleβ€”a simple Python file containing functions and variablesβ€”and import it locally into your scripts. This keeps your code organized, maintainable, and much easier to debug.


βš™οΈ What Is a Custom Module?

A custom module is just a Python file (with a .py extension) that contains definitions like functions, classes, or variables. You create it once and then import it into any other script that needs its functionality.

  • Any .py file you write can act as a module.
  • The module's name is the filename without the .py extension.
  • You can place your module in the same folder as your main script for simple local imports.

πŸ› οΈ How to Create and Import a Local Module

Step 1: Create your module file

Create a new file named my_helpers.py in the same directory as your main script. Inside it, define a simple function:

  • my_helpers.py contains: a function called greet(name) that returns a greeting string, and a variable called pi set to 3.14159.

Step 2: Import and use the module in your main script

In your main script (for example, main.py), you import the module using the import statement:

  • Write import my_helpers at the top of your script.
  • To call the function, use my_helpers.greet("Alice").
  • To access the variable, use my_helpers.pi.

Expected output when you run main.py:

  • my_helpers.greet("Alice") returns: Hello, Alice! Welcome to Python.
  • my_helpers.pi returns: 3.14159

πŸ“Š Importing Specific Parts of a Module

If you only need one function or variable from your module, you can import it directly using the from ... import ... syntax. This saves you from typing the module name every time.

  • from my_helpers import greet lets you call greet("Bob") directly without the my_helpers. prefix.
  • from my_helpers import pi lets you use pi directly.

Important note: If you import multiple items, separate them with commas: from my_helpers import greet, pi


πŸ•΅οΈ Understanding the Module Search Path

When you write import my_helpers, Python looks for the file in a specific order:

  • First, it checks the current directory (where your main script is running).
  • Then, it checks directories listed in the PYTHONPATH environment variable.
  • Finally, it checks the default installation paths for third-party libraries.

For local custom modules, simply keeping your module file in the same folder as your main script is the easiest and most reliable approach.


πŸ“‹ Comparison: Full Module Import vs. Specific Import

Aspect Full Module Import (import module) Specific Import (from module import item)
Syntax when using You must prefix with module_name. You use the item directly by name
Readability Very clear where the function comes from Less explicit, but cleaner for frequent use
Namespace pollution No risk of name conflicts Can overwrite existing names if you are not careful
Best use case When using many items from the module When using only one or two items frequently

πŸ§ͺ Practical Example: Organizing Utility Functions

Imagine you have several utility functions you use oftenβ€”like converting units or formatting dates. Instead of rewriting them, create a module called utils.py:

  • utils.py contains: celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f).

In your main script, you import it:

  • import utils
  • Call utils.celsius_to_fahrenheit(100) to get 212.0.
  • Call utils.fahrenheit_to_celsius(212) to get 100.0.

This keeps your main script clean and your reusable logic in one place.


⚠️ Common Pitfalls to Avoid

  • Naming conflicts: Do not name your module the same as a built-in Python module (like math.py or sys.py). This will override the standard library and cause unexpected errors.
  • Circular imports: If module A imports module B, and module B imports module A, you will get an error. Keep your imports flowing in one direction.
  • File location: If your module is not in the same folder, Python will not find it. Either move it to the same directory or adjust the PYTHONPATH.

βœ… Summary

Creating and importing custom modules locally is a fundamental skill that helps you write cleaner, more reusable code. You simply:

  1. Write your functions and variables in a .py file.
  2. Place that file in the same folder as your main script.
  3. Use import module_name or from module_name import item to bring its functionality into your script.

This approach saves time, reduces errors, and makes your projects much easier to maintain as they grow.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

This is how you import a Python file you wrote yourself from the same folder or a nearby folder.


πŸ”§ Example 1: Importing a module from the same folder

Create a file called tools.py in your project folder, then import it in another script.

# tools.py
def add(a, b):
    return a + b

def greet(name):
    return f"Hello, {name}"
# main.py (same folder as tools.py)
import tools

result = tools.add(5, 3)
print(result)

πŸ“€ Output: 8


πŸ”§ Example 2: Importing only a specific function from your module

Use from to bring in just the function you need, so you don't have to write the module name each time.

# tools.py (same as before)
def multiply(a, b):
    return a * b

def subtract(a, b):
    return a - b
# main.py
from tools import multiply

result = multiply(4, 6)
print(result)

πŸ“€ Output: 24


πŸ”§ Example 3: Importing a module from a subfolder

Place your custom module inside a subfolder named helpers, then use dot notation to import it.

# helpers/calculations.py
def square(x):
    return x * x

def cube(x):
    return x * x * x
# main.py (in the parent folder)
import helpers.calculations

value = helpers.calculations.square(5)
print(value)

πŸ“€ Output: 25


πŸ”§ Example 4: Using an alias for a long module path

Shorten the module name with as when the path is long or you want a cleaner name.

# helpers/calculations.py (same as above)
def double(x):
    return x * 2
# main.py
import helpers.calculations as calc

result = calc.double(9)
print(result)

πŸ“€ Output: 18


πŸ”§ Example 5: Importing all functions from a custom module

Use from module import * to bring every public function into your namespace (use sparingly).

# helpers/strings.py
def upper_case(text):
    return text.upper()

def lower_case(text):
    return text.lower()
# main.py
from helpers.strings import *

greeting = upper_case("hello world")
print(greeting)

πŸ“€ Output: HELLO WORLD


Comparison Table

Technique Syntax When to Use
Full module import import module_name You need multiple functions from the module
Specific function import from module_name import func You only need one or two functions
Subfolder import import folder.module_name Your module is inside a subfolder
Alias import import folder.module as alias You want a shorter name in your code
Wildcard import from module import * Quick prototyping (avoid in larger projects)