File tree Expand file tree Collapse file tree 1 file changed +16
-0
lines changed Expand file tree Collapse file tree 1 file changed +16
-0
lines changed Original file line number Diff line number Diff line change 3
3
import json
4
4
import subprocess
5
5
from importlib .metadata import PackageNotFoundError , requires , version
6
+ from importlib .util import spec_from_file_location , module_from_spec
6
7
from pathlib import Path
7
8
from sys import platform
8
9
@@ -302,3 +303,18 @@ def store_metadata_file(metadata_filename: str):
302
303
with open (metadata_filenamepath , "w+" ) as fh :
303
304
json .dump (metadata_json , fh , indent = " " )
304
305
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 )
You can’t perform that action at this time.
0 commit comments