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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Put the function in its own .py file, then import it in any other file that needs it. Each caller uses the same single copy of the code. A file named helpers.py can hold greet(), and app.py can run from helpers import greet and call it with its own arguments.

Create the module and import the function

A Python module is simply a .py file. Any function defined in it can be imported by name from another file. The steps below use two files in the same folder.

  1. Create a project folder, for example myproject, and open it in your editor.
  2. Create helpers.py in that folder and add the function:
    # helpers.py
    def greet(name: str) -> str:
        return f"Hello, {name}!"
    
  3. Create app.py in the same folder and import the function:
    # app.py
    from helpers import greet
    
    print(greet("Ari"))
    
  4. Run the caller from that folder with python app.py. The output is Hello, Ari!.

The definition lives in one place. If you later change the greeting text in helpers.py, every file that imports greet picks up the change the next time it runs. You do not need to copy the function into each file.

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

How Python finds the file

The import statement searches a list of locations for a matching module name and then binds the imported name in the importing file. When you run a script directly, Python places that script’s folder at the front of its search path. This is why app.py can find helpers.py when both sit side by side. Problems usually come from the folder you run the command from:

  • Running from a different folder. If you run python myproject/app.py from its parent directory, the import still works in most layouts because the script’s own folder is searched. If you run a file from a subfolder that does not contain helpers.py, you get ModuleNotFoundError: No module named 'helpers'.
  • Module lives elsewhere. If the module sits in a different folder, add that folder to PYTHONPATH. On Linux or macOS, use export PYTHONPATH=/path/to/folder. In Windows Command Prompt, use set PYTHONPATH=C:pathtofolder.
  • Wrong file name. The module name is the file name without .py. A file named helper.py cannot be imported as helpers.

Stop module code from running on import

Importing a module runs its top-level statements. If helpers.py contains a test call at the bottom, that call runs every time another file imports it. The fix is to place direct-run behavior under the __name__ == "__main__" check. Python sets __name__ to "__main__" only for the file you execute directly; for an imported module, __name__ holds the module’s own name.

# 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())

Now from helpers import greet loads the function without printing anything. Running python helpers.py calls main(), and the process exits with its return value. Keep the guarded block short and let main() hold the real behavior, so the code is easy to test.

Choose an import style

Python offers several ways to bring a function into a file. All of them run the same definition; they differ in how the call site reads and how names may collide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Import form How you call it Best for Trade-off
from helpers import greet greet("Ari") One or two functions used often The source module is not visible at the call site; a same-named function elsewhere can clash.
import helpers helpers.greet("Ari") Several functions from one module Slightly longer calls, but the origin of each name is explicit.
from helpers import greet as say_hello say_hello("Ari") Avoiding a name clash The alias can hide where the function came from if the file is read later.
from helpers import * greet("Ari") Not recommended for application code Brings in every public name, which makes it hard to see where names come from.

For most projects, the qualified form import helpers is the easiest to maintain once a project has more than a few modules.

Single module or package

The choice depends on how many reusable pieces you have and how they relate to one another.

Use a single module

A single helpers.py suits a small set of related functions that a few scripts share. It needs no extra structure, and anyone reading the project can find every function in one file.

Use a package

A package is a folder of modules. Once several groups of functions emerge, such as text handling, file handling, and date handling, a package keeps each group in its own file. A regular package has an __init__.py file in its folder, which can be empty.

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.
myproject/
    app.py
    utils/
        __init__.py
        text.py
        files.py

With this layout, app.py imports from the package with a full path:

# app.py
from utils.text import greet

print(greet("Ari"))

Inside the package, a module can use a relative import such as from .text import greet. Relative imports only work when the module is loaded as part of its package. If you run a file from inside utils/ directly, the relative import fails. Use absolute imports for files you plan to run directly.

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

Common mistakes and how to fix them

  • Naming a file after a standard-library module. A local file called random.py or json.py shadows the built-in module of the same name, so imports from the standard library break in confusing ways. Rename the file, for example to random_tools.py.
  • Circular imports. If a.py imports from b.py and b.py imports from a.py at top level, one of the names may not exist yet when it is needed. Move the shared function into a third module that both files import.
  • Print statements left at module top level. Output appears whenever the module is imported. Move the output into main() under the guard.
  • Relying on global variables. A function that reads a variable defined in the caller’s file cannot be reused elsewhere. Pass values in as arguments and return results, as the greet() function does.

Checklist before you reuse a function

  • The function takes its inputs as parameters and returns its result.
  • The module contains no top-level code except imports, definitions, and constants.
  • Direct-run behavior sits under if __name__ == "__main__":.
  • Each caller runs from a folder where Python can find the module, or PYTHONPATH includes that folder.
  • The module name does not match a standard-library or installed package name.

Python’s modules chapter in the official tutorial and the __main__ documentation in the language reference describe these behaviors in full.

“

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.

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