Importing multiple functions from a module in Python allows you to access specific functionality without loading the entire module namespace, making your code cleaner and more efficient. This is done using the from statement with comma-separated function names.
What You'll Need
- Python installed (version 3.6 or later recommended)
- A Python module (.py file) containing the functions you want to import
- A text editor or IDE to write and run your code
Step-by-Step
- Create or locate the module file (e.g.,
math_utils.py) containing the functions you want to import. For example: - In your main Python script (e.g.,
main.py), use thefromkeyword followed by the module name, thenimportand list the desired functions separated by commas. - Run your script using the command line:
python main.py. You should see the output of each function call. - Alternatively, you can import all functions from a module using the asterisk (
*) wildcard, though this is generally discouraged in larger projects due to potential namespace conflicts: - For better readability and to avoid ambiguity, especially when importing from multiple modules, consider using the
importstatement with an alias: - If the module is not in the same directory, ensure it is in your Python path. You can add a directory to the path using
sys.path.append():
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
raise ValueError("Cannot divide by zero")
# main.py
from math_utils import add, subtract, multiply, divide
Now use the imported functions
result1 = add(10, 5)
result2 = subtract(10, 5)
result3 = multiply(10, 5)
result4 = divide(10, 5)
print(f"Add: {result1}")
print(f"Subtract: {result2}")
print(f"Multiply: {result3}")
print(f"Divide: {result4}")
# main.py
from math_utils import *
print(add(10, 5)) # Works, but avoid in production code
# main.py
import math_utils as mu
print(mu.add(10, 5))
print(mu.subtract(10, 5))
# main.py
import sys
sys.path.append('/path/to/your/module')
from math_utils import add, subtract
print(add(1, 2))
Common Mistakes
- Forgetting to include the
.pyextension when referencing the module in thefromstatement — Python automatically looks for.pyfiles, so you should omit the extension (e.g.,from math_utils import add, notfrom math_utils.py import add). - Trying to import a function that doesn’t exist in the module — this raises an
ImportError. Always double-check function names and spelling. - Using
from module import *in large scripts or packages, which can overwrite existing variables or functions and make debugging difficult. - Assuming that importing a module runs its code every time — in reality, modules are only executed once per session unless reloaded.
- Not handling exceptions when importing functions that might fail (e.g., due to missing dependencies inside the module).
Tips
- Use explicit imports (
from module import func1, func2) instead ofimport *to improve code clarity and avoid namespace pollution. - Group related functions in a module and import only what you need — this keeps your code lightweight and maintainable.
- If you’re importing many functions from a module, consider whether importing the whole module with an alias (
import math_utils as mu) is clearer. - Use
__all__in your module to define which functions should be imported when usingfrom module import *:
# math_utils.py
__all__ = ['add', 'subtract', 'multiply', 'divide']
def add(a, b):
return a + b
... other functions
Helper function not intended for public use
def _internal_helper(x):
return x * 2
importlib.reload() if needed.Troubleshooting
- ModuleNotFoundError: This means Python cannot find the module. Check that:
- The module file exists in the current directory or in a directory listed in
sys.path. - The filename matches exactly (including case sensitivity on Linux/macOS).
- There are no typos in the module name.
sys.path. - The module file exists in the current directory or in a directory listed in
- ImportError: cannot import name 'func' from 'module': This occurs when the function name is incorrect or not defined in the module. Verify:
- The function is spelled correctly.
- It is defined at the top level of the module (not inside a function or class unless properly accessed).
- The module has been saved after editing.
- Whether the module has side effects (e.g., modifying global state) on import.
- If you’re accidentally importing from a different module with the same name (check
print(module.__file__)to see which file is being loaded). - That you’re not importing a built-in or third-party module with a conflicting name.
ImportError. Refactor to move shared code to a third module or use lazy imports inside functions.Frequently Asked Questions
Can I import functions with different names?
Yes, use the as keyword to alias a function during import: from math_utils import add as add_numbers. This is useful to avoid naming conflicts.
Is it better to import the whole module or specific functions?
Importing specific functions is preferred when you only need a few, as it makes dependencies clear and avoids cluttering the namespace. Import the whole module with an alias if you’re using many functions from it.
What happens if two modules have a function with the same name?
The last imported function will overwrite the previous one in the namespace. To avoid this, use module aliases (import math_utils as mu) or import with aliases (from math_utils import add as mu_add).
Can I import functions from a module inside a function?
Yes, you can place from module import func inside a function. This is called a lazy import and can improve startup time or avoid circular imports.
Do I need to reinstall Python to import a new module?
No. As long as the module file (.py) is in a directory Python searches (like the current folder or site-packages), you can import it immediately after saving.
Why does from module import * sometimes not import all functions?
If the module defines __all__, only the names listed in it are imported with *. Functions not in __all__ are considered internal and excluded.