To import a function from another Python file, use the syntax from filename import function_name, where filename is the name of your .py file without the extension. This allows you to reuse code across different scripts, keeping your project organized and preventing the need to rewrite the same logic multiple times.

What You'll Need

  • Python installed on your system (Python 3.x is recommended).
  • A code editor or IDE (such as VS Code, PyCharm, or a simple text editor).
  • Two or more Python files (.py) located within the same project directory for the simplest implementation.

Step-by-Step

  1. Create the source file: Create a Python file that contains the function you want to share. For example, create a file named calculations.py. Inside this file, define a function.

    def add_numbers(a, b): return a + b
    Save this file in your project folder.
  2. Create the destination file: Create a second Python file in the same folder where you want to use that function. For example, name this file main.py.
  3. Use the 'from...import' statement: At the top of main.py, tell Python which file to look in and which specific function to grab.

    from calculations import add_numbers
    Note that you do not include the .py extension in the import statement; Python knows to look for a file with that name ending in .py.
  4. Call the function: Now that the function is imported, you can call it directly by its name in main.py.

    result = add_numbers(10, 5) print(result)
    When you run main.py, it will execute the code inside calculations.py to perform the addition and print 15.
  5. Alternative: Import the entire module: If you have many functions in calculations.py and don't want to list them all, you can import the whole file.

    import calculations
    To use the function now, you must use the dot notation: calculations.add_numbers(10, 5). This is often preferred in larger projects because it makes it clear exactly which file a function came from.

Common Mistakes

One of the most frequent errors is including the file extension in the import line. Writing from calculations.py import add_numbers will result in a SyntaxError or ModuleNotFoundError because Python expects a module name, not a filename. Always omit the .py.

Another common mistake is naming your files after built-in Python libraries. For example, if you name your file math.py or random.py and then try to import math, Python may get confused between your local file and the official Python standard library. This leads to AttributeError because your local file likely doesn't have the same functions as the official library. Always use unique, descriptive names for your scripts.

Circular imports are also a significant pitfall. This happens when file_a.py imports something from file_b.py, and file_b.py simultaneously tries to import something from file_a.py. This creates an infinite loop that Python cannot resolve, resulting in an ImportError. To avoid this, restructure your code so that shared functions are moved to a third, neutral file that both files can import from.

Finally, beginners often forget that the files must be in the same directory (or in a properly configured Python package) for a simple import to work. If main.py is in a folder called /app and calculations.py is in a folder called /utils, a simple from calculations import ... will fail because Python does not automatically search every folder on your hard drive.

Tips

To prevent code from running automatically when you import a file, use the if __name__ == "__main__": block. If you have print statements or test code in calculations.py, they will execute the moment you import that file into main.py. By wrapping your test code in this block, you ensure that the code only runs if calculations.py is executed directly, not when it is imported as a module.

Example for calculations.py:
def add_numbers(a, b): return a + b if __name__ == "__main__": print("Testing function:", add_numbers(2, 2))

For better organization in larger projects, group related functions into folders. If you put calculations.py inside a folder named tools, you can import it using from tools.calculations import add_numbers. In older versions of Python, you needed a file named __init__.py (even if empty) inside the folder to make it a package, but in Python 3.3+, this is often optional (known as implicit namespace packages), though still recommended for clarity.

If you find yourself importing a large number of functions from one file, consider using from calculations import *. While this imports everything, it is generally discouraged in professional coding because it clutters your namespace and makes it difficult to track where a function originated, which can lead to bugs if two different modules have functions with the same name.

Troubleshooting

If you encounter a ModuleNotFoundError, the first step is to verify the file path. Ensure that the file you are importing is in the same directory as the script you are running. Check for typos in the filename; remember that Python is case-sensitive, so Calculations.py is different from calculations.py.

If the file is in a different directory, you have a few options. The simplest is to move the files into the same folder. If that is not possible, you can add the path to the folder manually using the sys module. Add these lines to the top of your main script:
import sys sys.path.append('/path/to/your/folder') from calculations import add_numbers
Replace '/path/to/your/folder' with the actual absolute path to the directory containing your source file.

If you get an AttributeError saying the module has no attribute 'function_name', double-check that you saved the source file after adding the function. It is common to write a function in one tab of an editor but forget to hit Ctrl+S (or Cmd+S) before running the import script in another tab. Python reads the file from the disk, not from the unsaved buffer in your editor.

If you suspect a circular import, look at your import statements in both files. If they point to each other, move the shared logic to a new file. For example, if user.py and auth.py import each other, create a constants.py or utils.py file, put the shared logic there, and have both user.py and auth.py import from that new file instead.

Frequently Asked Questions

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

Not by default. Python searches the current directory and the system path. To import from a parent folder, you usually need to add the parent directory to sys.path or run your script as a module using the -m flag from the project root.

What is the difference between 'import module' and 'from module import function'?

import module imports the entire namespace, requiring you to use module.function(). from module import function brings the specific function directly into your current namespace, allowing you to call function() without the prefix.

Does importing a function slow down my program?

The initial import takes a small amount of time because Python must locate and compile the module to bytecode. However, once imported, calling the function is just as fast as if it were defined in the same file. The overhead is negligible for most applications.

Can I rename a function while importing it?

Yes, you can use the as keyword to give a function an alias. For example, from calculations import add_numbers as add allows you to call the function using add() instead of add_numbers(). This is useful for avoiding name conflicts.

Do I need to install the other .py file as a package?

No, you do not need to use pip or create a formal package to import from another file on your local machine. As long as the file is accessible via the Python path, a standard import statement will work.