Ernie Peters
Ernie Peters

Reputation: 697

Dynamically import class by name from module imported as:

I have searched high and low and can't find a proper solution.

I need to dynamically create objects and store them in dictionaries using a for loop from a class that is in a different file.

To avoid name space pollution I like to import my modules like so:

from my_folder import my_file as mf

the loop looks like this:

self.my_dict = {} # create empty dictionary

    for F in ('One', 'Two', 'Three', ...):
        object = F(var1, var2)
        self.my_dict[F] = object

on the line object = F(var1, var2) I need the F be referring to mf.One, mf.Two and so on.

How do I append the value F to mf so it reads it as mf.value-of-F instead of reading it as mf.F?

I know I must be missing something very obvious, just not obvious to me right now. Thanks

Upvotes: 0

Views: 194

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385910

There are almost certainly better solutions to your problem, but your example is so short and contrived that it's hard to give good advice.

To address the specific question you asked, you can use getattr to get a function or class from a module based on a string:

for F in ('One', 'Two', 'Three', ...):
    Cls = getattr(mf, F)
    obj = Cls(var1, var2)
    self.my_dict[F] = obj

A simpler approach might be to iterate over the classes themselves:

for F in (mf.One, mf.Two, mf.Three):
    obj = F(var1, var2)
    ...

Upvotes: 1

Valner
Valner

Reputation: 36

Try to use such syntax:

object = mf.__dict__[F](var1, var2)

Upvotes: 1

Related Questions