Skip to content

Commit b8a9902

Browse files
committed
Implemented utility method to dynamically import class from file
1 parent 04baf7d commit b8a9902

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

kernel_tuner/file_utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44
import subprocess
55
from importlib.metadata import PackageNotFoundError, requires, version
6+
from importlib.util import spec_from_file_location, module_from_spec
67
from pathlib import Path
78
from sys import platform
89

@@ -302,3 +303,18 @@ def store_metadata_file(metadata_filename: str):
302303
with open(metadata_filenamepath, "w+") as fh:
303304
json.dump(metadata_json, fh, indent=" ")
304305

306+
def import_class_from_file(file_path: Path, class_name):
307+
"""Import a class from a file."""
308+
module_name = file_path.stem
309+
spec = spec_from_file_location(module_name, file_path)
310+
if spec is None:
311+
raise ImportError(f"Could not load spec from {file_path}")
312+
313+
# create a module from the spec and execute it
314+
module = module_from_spec(spec)
315+
spec.loader.exec_module(module)
316+
if not hasattr(module, class_name):
317+
raise ImportError(f"Module '{module_name}' has no class '{class_name}'")
318+
319+
# return the class from the module
320+
return getattr(module, class_name)

0 commit comments

Comments
 (0)