Python 3
execfile alternative
import a file Python
execute Python script
Python file inclusion
What alternative is there to execfile in Python 3? / How to include a Python file?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Python 2, `execfile()` was a convenient built-in function used to execute Python scripts directly from other Python scripts. However, in Python 3, `execfile()` was removed as it poses several security risks and the need for the function can be efficiently managed using alternatives. This article will explore how you can include and execute the contents of one Python file from another in Python 3, with techniques that ensure efficiency and security.
Alternative to `execfile()` in Python 3
Using `exec()` with `open()`
While `execfile()` is not available in Python 3, you can mimic its behavior by using `exec()` with an open file. Here's how you can do it:
- Explanation: This opens the desired file in read mode and executes its content in the current namespace using `exec()`. However, beware of the security and maintainability issues associated with this approach. Executing arbitrary code can lead to security vulnerabilities if the content of the file is not trusted.
- Explanation: By defining functions or classes in `script.py`, you can import them into `main.py`. This provides a clear separation of functionality and makes the code reusable and testable.
- Explanation: `importlib.import_module(module_name)` imports the target module dynamically at runtime. This method is particularly useful in scenarios where the module name is determined programmatically.
- Explanation: `runpy.run_path()` allows for running a file path as a program, essentially similar to executing the file directly as the main script.
- Why `execfile()` Was Removed: In an effort to improve security and maintainability, `execfile()` was removed from Python 3. Its inherent ability to run arbitrary code could lead to serious vulnerabilities if misused.
- Recommendations: Ensure that scripts being executed are from trusted sources. Avoid using `exec` and similar techniques with untrusted input.
- Efficiency: Using Python's built-in import system with modules is generally more efficient and manageable once the initial setup is complete.
- Load Time: Dynamically loading modules through `importlib` or `exec` can introduce overhead, especially in large projects. Plan the structure of your application actively to minimize unnecessary imports.
- Best Practices: Keeping code within functions and classes increases testability and maintainability. Documentation becomes easier and comprehensive, serving as a true reflection of code intention.
- Refactoring: Regularly refactor code to separate concerns and maintain logical boundaries. This aligns with the philosophy that “Readability counts” in Python.

