1

I have:

from pathlib import Path
if some_condition:
    path1 = Path(r'path/to/file.py')
else:
    path1 = Path(r'path/to/other_file.py')

And I want to dynamically import class class1 from that path (both file.py and other_file.py have a class named class1). How can I do that?

UPDATE:

I managed to get the module object successfully:

import importlib.util

file_name = path1.name

spec = importlib.util.spec_from_file_location(file_name, path1)
module = importlib.util.module_from_spec(spec)

But I still don't know how to get class1 from the module object.

omer mazig
  • 965
  • 2
  • 10
  • 17
  • `path1`'s value is acquired dynamically. I changed the example to reflect that. – omer mazig Dec 03 '20 at 10:17
  • Did you read this post? https://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class From the first answer of Jason Baker: " What you're basically wanting to do is this: from my_package.my_module import my_class" It seems to me very similar to what you want to do – Wippo Dec 03 '20 at 10:54
  • Yeah but he has something like `path.to.file`, while I can have `r'c:/folder_that_is_not_even_in_the_package/package_name/path/to/file.py'`. I guess I can write something to convert between the two but that seems wrong – omer mazig Dec 03 '20 at 11:13
  • 1
    In case someone else needs it. Your solution almost works, but you need `spec.loader.exec_module(module)` after `module = importlib.util.module_from_spec(spec)`. – iLoveTux Aug 18 '22 at 16:20

0 Answers0