1

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'].

1 Answer 1

1

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').

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.