0

I have read this related question, but I haven't been able to apply any of the given answers.

I have several test scripts, all using the same function implemented in a common file.

The common file begins with the following import statements:

from Class1       import          Class1
from Class2       import Type1 as Class2
from Class3       import Type1 as Class3
from Class4       import          Class4
from Class5.Type1 import          Class5
from Class6.Type1 import          Class6

I'd like to be able to change Type1 for some of the test scripts.

At present, I just take the relevant statements out of the common file, and place them in each one of the test files with the type which is to be tested.

But I am looking for a "nicer" way, for example, pass a string which represents the type, and import dynamically according to that input string.

This would allow me to minimize the test scripts.

I guess I would probably need to place the import statement inside the function called by the test scripts, but I'm fine with that.

How exactly can I achieve this?

I haven't tried the infamously known eval because:

  1. It is evil
  2. I'm pretty sure that it doesn't work for "non-read-only" expressions
halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61

1 Answers1

0

You can use the built-in importlib module

import importlib

type_str = function_that_determines_this_val()
module = importlib.import_module(module)
obj = getattr(module, type_str)

Not sure this is exactly what you're looking for but importlib is probably what you're looking for.

n8sty
  • 1,418
  • 1
  • 14
  • 26