To import functions from another Python file, use the import statement followed by the module name (the filename without the .py extension), then call the function with module.function(), or use from module import function to call it directly. For example, if you have a file named math_utils.py containing def add(a, b): return a + b, you can write from math_utils import add and then use add(2, 3).
Why Imports Matter in Python
Python organizes code into modules and packages, which are simply files and folders containing Python code. Importing lets you reuse functions, classes, and variables across multiple files without copying and pasting. This is fundamental to writing maintainable code: you can split a large script into logical parts, test them individually, and avoid name conflicts. The import system also loads a module only once per interpreter session, so repeated imports are efficient.
Basic Import Syntax and Variations
There are several ways to import, each with trade-offs:
import module_name– Imports the whole module. Access functions withmodule_name.function(). This keeps the namespace clean because all names are prefixed.from module_name import function_name– Imports a specific function directly. Call it without the module prefix. This can lead to name clashes if you import two functions with the same name.from module_name import *– Imports all public names from the module. This is generally discouraged because it pollutes the namespace and can hide errors.import module_name as alias– Gives the module an alternative name, useful for long module names or to avoid conflicts.
Example: if helper.py contains def greet(name): return f"Hello, {name}", you can do:
import helper
print(helper.greet("Alice")) # Output: Hello, Alice
from helper import greet
print(greet("Bob")) # Output: Hello, Bob
How Python Finds the File
When you write import mymodule, Python searches for mymodule.py in a list of directories defined by sys.path. This list includes:
- The directory of the script you are running (or the current working directory in interactive mode).
- Directories listed in the
PYTHONPATHenvironment variable. - Standard library and site-packages directories.
If the file is in a different folder, you have a few options:
- Place the file in the same directory as your main script.
- Add the folder to
sys.pathat runtime (e.g.,sys.path.append('/path/to/folder')) – but this is a quick fix, not a long-term solution. - Use a package: create a folder with an
__init__.pyfile (can be empty) and import asfrom folder import module.
Relative Imports for Packages
When working inside a package (a folder with __init__.py), you can use relative imports to reference sibling modules. For example, if you have a package myproject/ with __init__.py, utils.py, and main.py, inside main.py you can write from .utils import helper. The single dot means “current package”. Two dots (..) go up one level. Relative imports only work inside packages, not in standalone scripts run directly.
Common Problems and Solutions
Beginners often hit a few snags:
- ModuleNotFoundError – Python can’t find the file. Check the file name, spelling, and location. Ensure the file is in the same directory or adjust
sys.path. - NameError: name ‘function’ is not defined – You forgot to import it, or you used
import moduleand then tried to callfunction()without the module prefix. - Circular imports – Two files import each other. This happens when module A imports from B and B imports from A. To fix, move shared code to a third module, or import inside a function instead of at the top of the file.
- Unintended code execution – If your module has top-level code (like print statements or function calls) outside of a
if __name__ == "__main__":block, it runs on import. Always guard test code with that condition to prevent side effects.
Organizing Code for Reusability
To make importing smooth, follow these practices:
- Keep module names lowercase and avoid hyphens (use underscores).
- Put all imports at the top of the file.
- Use
if __name__ == "__main__":for code that should only run when the file is executed directly, not when imported. - Group related functions into modules, and related modules into packages.
- Consider using a virtual environment and installing your package with
pip install -e .for larger projects, so the package is always importable.
Alternatives to Importing
Importing is the standard way to reuse code, but there are alternatives for specific cases:
- Executing another script: Use
exec(open('file.py').read())to run the code, but this is messy and discouraged because it doesn’t create a proper module namespace. - Copy-pasting code: Works for tiny snippets but leads to maintenance nightmares.
- Using a single large file: Simpler for small projects, but becomes hard to navigate as it grows.
- Dynamic import: Use
importlib.import_module('module_name')when you need to import a module whose name is known only at runtime.
Frequently Asked Questions
Can I import a function from a file in a different directory? Yes, but you need to make sure that directory is in Python’s search path. You can add it to sys.path temporarily, or better, structure your project as a package and use relative imports.
What does if __name__ == "__main__": do? It checks whether the file is being run directly (as a script) or imported as a module. Code inside this block only runs when the file is executed directly, preventing side effects when you import the module.
Why does my import run the whole file? Because Python executes all top-level code in a module when it is imported. If you have print statements or function calls at the top level, they run. Wrap them in the if __name__ guard to prevent that.
What’s the difference between import module and from module import function? The former gives you access to the whole module, so you must use module.function(). The latter imports only the specific function, so you can call it directly. The former is safer for avoiding name conflicts.
How do I import a module that is in a subfolder? If the subfolder is a package (has __init__.py), use from subfolder import module or from subfolder.module import function. If it’s not a package, you may need to add the subfolder to sys.path.
Can I import all functions from a module at once? Yes, with from module import *, but it’s not recommended because it makes it unclear which names are available and can overwrite existing names.
Related
- Cell Counting and Viability: Methods Explained
- Split String SQL Server: Best Methods
- Google Sheets Split Cell Into Two: 3 Easy Ways
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Day of Week from Date: Formulas and FormattingIf your date is in A2, enter =TEXT(A2,"dddd") to show its full weekday name; for example, an actual…
- Union Function in BigQuery: Syntax & ExamplesThe UNION function in BigQuery is not a standalone function but a set operator (UNION ALL and UNION…
- Excel: How Many Days Between Dates? Simple FormulasTo find how many days separate two dates in Excel, subtract the start date from the end date:…
- Combine Names in Excel: Join Two Cells with a FormulaWith a first name in A2 and a last name in B2, enter =A2&" "&B2 in another cell…
- Excel Formula for Counting Unique Text ValuesThe fastest formula for counting unique text values in Excel is =SUMPRODUCT(--(COUNTIF(range,range>"">0))) for a single column, but the…
- VLOOKUP from Another Workbook: How ToYes, you can use VLOOKUP to pull data from another workbook by including the workbook name and sheet…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.