Created
July 13, 2024 14:52
-
-
Save cmower/ef2496ace8ac15e5a9d9f22954ed920c to your computer and use it in GitHub Desktop.
Given a function name (string), and a path to a Python script (string), import the function from the script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import importlib.util | |
from typing import Callable | |
def import_from_file(script_path: str, function_name: str) -> Callable: | |
""" | |
Imports a function from a Python script file given the file path and the function name. | |
Args: | |
script_path (str): The file path of the Python script. | |
function_name (str): The name of the function to import from the script. | |
Returns: | |
function (Callable): The function handle for the specified function name. | |
Raises: | |
FileNotFoundError: If the script file does not exist. | |
AttributeError: If the function with the given name does not exist in the script. | |
ImportError: If there is an error in importing the module. | |
""" | |
# Get the module name from the script path | |
module_name = os.path.splitext(os.path.basename(script_path))[0] | |
# Load the module from the given script path | |
spec = importlib.util.spec_from_file_location(module_name, script_path) | |
module = importlib.util.module_from_spec(spec) | |
sys.modules[module_name] = module | |
spec.loader.exec_module(module) | |
# Get the function from the loaded module | |
function = getattr(module, function_name) | |
return function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment