Loading classes dynamically

R

Ramza Brown

What is the most pythonic way to load a class and instaniate an object
dynamically. Right now, I am using eval:

try:
load = eval('%s(props)' % (props['plugin.generate']))
except:

It works, doesnt seem very safe. Where props['plugin.generate'] is a
class name string. And 'props' is the first arg in the constructor.

What do you think?
 
S

Steven Bethard

Ramza said:
try:
load = eval('%s(props)' % (props['plugin.generate']))
except:

It works, doesnt seem very safe. Where props['plugin.generate'] is a
class name string. And 'props' is the first arg in the constructor.

Where is the class defined? The right answer to this is usually
somethign like:

load = getattr(some_module, props['plugin.generate'])(props)

If the class is defined in the current module, another possibility is:

load = globals()[props['plugin.generate']](props)

HTH,

STeVe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,311
Members
47,986
Latest member
ColbyG935

Latest Threads

Top