John
John

Reputation: 2147

How to import a class on the-fly-and Instantiate it as an object?

I know we could use exec to load a module ( from a string ) on-the-fly

e.g.

path  = 'A.B'
class = 'C'
exec( "from %s import %s" %(path, class) )

but how I could instantiate it as an object c? btw, is above the best way to load a module from a string? it does not look very safe. thanks

regards, John

Upvotes: 2

Views: 806

Answers (2)

ekhumoro
ekhumoro

Reputation: 120608

For python<=2.6, you can use the built-in __import__ function:

m = __import__('A.B', globals(), locals(), ['C'])
C = getattr(m, 'C')
c = C()

Upvotes: 4

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

import importlib
m = importlib.import_module('A.B')
C = getattr(m, 'C')
c = C()

You can get importlib from 2.7 standard library, if you're on a lower version, for some weird reason.

Upvotes: 1

Related Questions