Daniel B.
Daniel B.

Reputation: 709

How to load a Class from File given only its String specification in Python?

I intend to let a user decide during runtime (in my Python 3.8 program) which class from a given set of classes to load for executing some actions. For example, if we were talking about food, the user could decide whether to go for eggs or sausage. Both these classes are defined in one or multiple separate file(s), (both of which are) contained in a known folder.

Now, my question is how to load the corresponding class eggs given the string representation eggs (entered by a user). I saw that a method __import__ exists which is meant to solve exactly such issues. According to the documentation, one could get access to class eggs defined in spam.ham by executing:

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs

which is equivalent to from spam.ham import eggs.

The problem with this example is that it assumes the code snippet _temp.eggs, which is not given/known a priori in my case. Therefore, I would like to know how to transform eggs = _temp.eggs into some statement where _temp.eggs is replaced by some statement where .eggs is replaced by some string representation of eggs.

For example, given _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1), I am looking for some command like eggs = _temp['eggs'].

Upvotes: 1

Views: 32

Answers (1)

Daniel B.
Daniel B.

Reputation: 709

As it turns out, given the starting point:

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) 

the problem eventually boils down to that of retrieving an object's attribute by the attribute's name.

The answer to that problem can be found here.

Hence, given _temp, class eggs can be accessed by eggs = getattr(_temp, 'eggs').

Upvotes: 1

Related Questions