PascalVKooten
PascalVKooten

Reputation: 21481

Dynamic multiple inheritance in Python

I'm having a combination of "backend" together with a "type".

Backends: Cloudant, ElasticSearch, File, ZODB

Types: News, (potentially others)

So I'm now defining classes like:

Plugin
PluginCloudant (which inherits from Plugin)
PluginNews (which inherits from Plugin)

The combined class is then:

class PluginCloudantNews(PluginCloudant, PluginNews)

Now, I'd like to dynamically allow people to define a Service (which takes a Plugin as an argument).

The service's implementation will only rely on the backend, so it seems like that part of the class should automatically be used.

My point is, I shouldn't have to give PluginCloudantNews as argument to the service (since the Cloudant part is a logical consequence of being in the Cloudant service), so rather the less specific PluginNews.

How can I just pass PluginNews to the Service class (the type), but still end up with the PluginCloudantNews functionality?

Some kind of dynamic inheritance...

It should glue together PluginCloudant with class PluginNews, or other type, which are all defined upfront.

Upvotes: 0

Views: 231

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17781

I'm not sure I have fully understood your question, however you can "dynamically" construct class objects using the type builtin. The following two lines produce the same result:

class PluginCloudantNews(PluginCloudant, PluginNews): pass

PluginCloudantNews = type('PluginCloudantNews', (PluginCloudant, PluginNews), {})

As you can see, type() takes three arguments: the name of the new class, a list of base classes to inherit from, a dictionary with the attributes to add to the new class.

Upvotes: 1

Related Questions