The easiest way to reuse code between Python files is to import methods directly, but doing it wrong can lead to errors, conflicts, or cluttered imports. This guide shows you the cleanest, most reliable methods to import functions, classes, and modules from another file, including when they’re in the same directory or a different package.

What You'll Need

  • Two Python files where you want to import code from one to another (e.g., `main.py` and `utils.py`).
  • A basic understanding of Python’s module system (you can skip this if you’re already familiar).
  • Python installed (3.6+ recommended).
  • An editor or IDE (VS Code, PyCharm, or even Notepad++) to create and test your files.
  • Knowledge of how your code is structured (e.g., whether functions/classes are defined at the top level or nested).

Step-by-Step

1. Organize Your Files in a Directory

Place the files you want to import in the same folder or in a folder that matches Python’s package structure. For example:

  1. project_folder/ contains: main.py (file importing from another) and utils.py (file being imported).

If you’re working inside a package (a folder with an empty __init__.py), import from subfolders using full paths (e.g., from package.subfolder import module).

2. Define the Functions or Classes in the Source File

In utils.py, define the code you want to reuse, such as functions or classes. Avoid global variables unless necessary.

  1. Example utils.py:
    def greet(name):
            "Hello, " + name
    
    def calculate_discount(price, discount_percentage):
            "Discount applied: " + str(price * (discount_percentage / 100))
    
    class Calculator:
            def __init__(self, operation):
                    self.operation = operation
    
            def compute(self, a, b):
                    return a + b if self.operation == "add" else a * b

3. Import the Code in Your Target File

In main.py, use one of the three main import methods:

  1. Import the entire module:
    import utils

    Then use functions/classes with module_name.function syntax:

    result = utils.greet("John")
    print(result)  # Output: "Hello, John"
  2. Import specific functions/classes:
    from utils import greet, calculate_discount, Calculator

    Now you can use them directly:

    calculator = Calculator("add")
    result = calculator.compute(5, 7)
    print(result)  # Output: 12
  3. Import with an alias:
    import utils as utl

    Use the alias instead of the full module name:

    print(utl.greet("Alice"))

4. Handle Circular Imports (If Needed)

If both files import from each other (e.g., main.py imports from utils.py, and vice versa), avoid infinite loops by:

  1. Restructuring code into a third file or package.
  2. Using conditional imports (e.g., if __name__ == "__main__": in the imported file).
  3. If Python allows it, use from utils import * (but this is discouraged for clarity).

Example of a "safe" import guard in utils.py:

if __name__ == "__main__":
    # Only run this if the script is executed directly (not imported)
    print(greet("Test"))

Common Mistakes

  • Forgetting to save the file: Changes won’t appear until you save and restart the Python interpreter. Always check for typos after editing.
  • Assuming the module is in the Python path: If files are in a subfolder not listed in sys.path, Python won’t find them. Either move them into your project root or update sys.path.
  • Overusing wildcards: Imports like from utils import * pollute the namespace and make debugging harder. Prefer explicit imports.
  • Ignoring file naming conventions: Python modules must follow the naming rule (lowercase with underscores only). Avoid names like MyFile.py.
  • Not testing after importing: Errors may appear silently if functions/classes aren’t defined correctly in the source file.

Tips

  • Use relative imports for submodules: If utils.py is inside a package, import from it as from . import utils (dot means "current package").
  • Organize imports in your scripts: Group imports by type (standard library, third-party, local) for readability.
  • Leverage docstrings: Document imported functions/classes clearly to explain their purpose and usage.
  • Avoid redefining functions: If two files import the same function, Python will replace the first with the last one. Use namespaces or rename functions if needed.
  • Test interactively: Use a Python shell to test imports before writing full scripts.

Troubleshooting

What If Python Can’t Find the Module?

  1. Check file paths: Run python -c "import sys; print(sys.path)" to see where Python looks for modules. Your file must be in one of these locations.
  2. Use absolute imports: For subfolders, use from package.subfolder import module instead of relative paths.
  3. Add the folder to Python path: If files are in a subfolder, run:
    import sys
    sys.path.append("/path/to/your/project/folder")
    import utils
  4. Verify file extensions: Ensure the file ends with .py (not .pyc, which are bytecode files).

What If You Get NameErrors?

  1. Double-check the function/class name: Typos in the import statement cause these errors. Use an IDE’s autocompletion feature.
  2. Check if the file is saved: Python may not detect changes until you restart the interpreter.
  3. Re-import the module: Run del utils (if already imported) before re-importing to clear old references.

What If Circular Imports Cause Errors?

  1. Restructure your code: Move shared logic into a third file or use conditional logic (e.g., if __name__ == "__main__":).
  2. Use lazy imports: Import functions/classes only when needed (e.g., if some_condition: import utils).
  3. Avoid direct imports between files: If possible, use a third module for shared logic.

Frequently Asked Questions

How do I import a function from a file in a different directory?

Add the directory to your Python path using sys.path.append("/path/to/directory") before importing. Alternatively, move the file into your project root or use relative imports with from .. import file (adjust the dots based on folder structure).

Can I import Python files from an external website?

No, you can’t directly import external Python files (like utils.py from GitHub) into your local script. If you need third-party code, use packages from PyPI (e.g., pip install package_name).

Why does my script work in the editor but not when run from the command line?

This often happens due to Python’s module search path. The editor might add your project folder to sys.path automatically, but the command line doesn’t. Either: - Use python -m pip install -e . (for virtual environments) and activate it, or - Run PYTHONPATH="path/to/your/project" python script.py.

How can I import a class from a file that’s inside a package?

Use absolute imports. If your structure is: my_package/ ├── __init__.py ├── utils/ │ ├── __init__.py │ └── my_file.py then import from my_package.utils.my_file inside another script. If the script is in the same package, use from .utils.my_file import ClassName (dot means "current package").

What’s the difference between import utils and from utils import greet?

import utils allows you to use any function/class from utils.py (e.g., utils.greet()), while from utils import greet lets you use greet() directly. The former is more explicit for large modules.

How do I avoid importing everything from a file with from utils import *?

This is a common anti-pattern. Instead: - Import only what you need (e.g., from utils import function1, function2). - Use a helper function or module to expose only specific exports. - Document which functions/classes are intended for public use.