October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

Write a Python Function Once and Call It From Any File

Put a Python function in its own module, import it wherever it is needed, and guard direct-run code so importing stays quiet. Setup steps, import styles, packages, and fixes for common errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the function in its own .py file, then import it into any other file that needs it. Every caller runs the same code, so a fix made in one place applies everywhere the function is used. The rest of this guide shows the exact setup, the two import styles, how to stop a file from running its test code when it is imported, and how to fix the errors people hit most often.

Create the module and the function

A Python module is simply a .py file. Any function defined at the top level of that file can be imported by another file in the same folder. The steps below use a small example with two files.

As an Amazon Associate I earn from qualifying purchases.

  1. Create a project folder, for example myproject, and open it.
  2. Create helpers.py and add the function:
    # helpers.py
    def greet(name: str) -> str:
        return f"Hello, {name}!"
    
  3. In the same folder, create app.py and import the function:
    # app.py
    from helpers import greet
    
    print(greet("Ari"))
    
  4. From inside myproject, run python app.py. The expected output is Hello, Ari!

Python can find helpers.py because the folder of the script being run is on the module search path. That is why running the command from a different folder is the most common cause of a missing-module error, covered below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an import style

There are two common ways to bring a function into another file. Both call the same code; they differ in how the call site reads.

Style Import line How you call it Best when Watch out for
Direct import from helpers import greet greet("Ari") You import a few specific names and want short calls. If two modules export the same name, the later import silently replaces the earlier one.
Module import import helpers helpers.greet("Ari") The file uses functions from several modules and you want each call to show its source. Calls are longer, and you must type the module name each time.
Aliased import from helpers import greet as hello hello("Ari") A name is long or clashes with something already in the file. Readers may not recognise the original name, so use aliases sparingly.

For a file that uses one or two helpers, the direct form is the most readable. Once a file pulls in functions from many modules, the module form makes the origin of each call obvious during code review.

Stop module-level code from running on import

Importing a file runs every statement at its top level once. If a file contains a test call or a print statement outside any function, that code runs in every file that imports it. Consider this file:

# noisy.py
print("Loading noisy module...")

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

Any file that runs from noisy import greet prints Loading noisy module... before the function is available. The fix is to keep top-level code limited to imports, definitions, and constants, and to place anything meant for direct execution under a guard:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
# helpers.py
def greet(name: str) -> str:
    return f"Hello, {name}!"


def main() -> int:
    print(greet("Ari"))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

The guard works because Python gives an imported module its own name, such as helpers, while the file that is run directly receives the name __main__. The condition is therefore true only when you run python helpers.py, and the demonstration call is skipped when another file imports the function. Returning an integer from main() and passing it to SystemExit lets the exit status signal success or failure to the shell.

Single module or package?

The choice depends on how much reusable code you have and how it groups together.

One module for a small, cohesive set of functions

A single file such as helpers.py is the right size when the functions share a purpose and the file stays readable, roughly a few hundred lines or less. Splitting it too early adds folders without adding clarity.

A package when related code grows

A package is a folder of modules. Add an __init__.py file to mark the folder as a package; it can be empty. Here is a layout with two related modules:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
myproject/
    app.py
    tools/
        __init__.py
        text.py
        dates.py

The functions go in the modules:

# tools/text.py
def slugify(title: str) -> str:
    return "-".join(title.lower().split())
# tools/dates.py
from .text import slugify

def dated_slug(title: str, day: str) -> str:
    return f"{day}-{slugify(title)}"
# app.py
from tools.text import slugify
from tools.dates import dated_slug

print(slugify("Write Once Call Anywhere"))
print(dated_slug("Write Once", "2026-10-09"))

Running python app.py from myproject prints write-once-call-anywhere and then 2026-10-09-write-once. The line from .text import slugify is a relative import, which works only inside a package. Python’s documentation covers both absolute and relative import forms in its modules tutorial.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When Python cannot find or load your function

Most import failures fall into a few patterns. Check them in this order:

  • ModuleNotFoundError: No module named ‘helpers’. You are running the script from a folder that does not contain helpers.py, or the file has a different name. Run the command from the project root, and confirm the file name matches the import exactly, including capitalisation.
  • ImportError: cannot import name ‘greet’. The module loaded, but the name is missing. Look for a misspelling, a function defined inside another function or inside an if block, or a different file that you are importing by mistake.
  • The module imports but behaves like an older version. A session that stays open keeps the module it loaded earlier. Run the script again from a fresh process, or in an interactive session call importlib.reload(helpers) after editing the file.
  • Standard-library functions suddenly break. A local file named after a standard-library module, such as random.py, json.py, or email.py, shadows the real module for everything in that folder. Rename your file.
  • Circular imports. If a.py imports from b.py and b.py imports from a.py, one of the names may not exist yet when it is needed. Move the shared function into a third module that both files can import.

Write functions that travel well

A function that moves between files stays reusable only if it does not depend on where it was written. Pass in every value it needs as an argument instead of reading a global variable, and return results instead of printing them. Keep input prompts, file paths tied to one machine, and application-specific settings in the calling code. A function written this way can be imported unchanged into a script, a web view, or a test.

Frequently Asked Questions

Can I import a function from a file in a different folder?

Yes. The simplest route is to add that folder to the PYTHONPATH environment variable so Python searches it. For a larger project, turn the shared code into a package and install it into your environment with pip, using an editable install (pip install -e .) while you are still changing it. Avoid editing sys.path inside your code unless there is no other option, because it makes the program’s behaviour depend on the location it runs from.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do I need to restart Python after editing the file that holds my function?

Not when you run a script again with python app.py, because each run starts a new process and loads the current file. Only a long-running interactive session keeps the old version in memory, which is the case where importlib.reload is useful.

The Bottom Line

Define the function once in a module, import it with from module import name or import module, and guard any direct-run code with if __name__ == "__main__":. Start with a single file, move to a package only when related modules multiply, and run commands from the project root to avoid most import errors.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.