Reputation: 4647
I want to be able to dynamically specify a class reference from a dynamically specified module and pass that class reference to a third party library which then uses it. But I don't want to call the class itself (and thus the __init__
method in the class) when I do so, that's for the library to do.
I currently have this:
import importlib
import thirdpartylib
# Load the module
the_module = importlib.import_module('my_module')
# Now the class
the_class = getattr(the_module, 'MyClass')()
thirdpartylib.process(the_class)
But of course, getattr()
runs the __init__
method, which I don't want.
How do I pass a reference to a class without creating an instance and triggering __init__
?
Upvotes: 0
Views: 46
Reputation: 23256
the_class = getattr(the_module, 'MyClass')
This would be the class.
the_class = getattr(the_module, 'MyClass')()
This is an instance of the class. You have to remove the trailing ()
.
Upvotes: 2