Ben Hoff
Ben Hoff

Reputation: 1108

Filter for instances of classes in python

I'm making a plugin manager in python. My plan is to append all of my possible plugins (which could consist of classes, functions, and instances of classes) to a single list and then use custom filter functions to get out the appropriate objects.

How do you get all class instances out of a list? The class instances can be of any class.

example:

class A:
    pass

def func():
    pass

instance_a = A()

plugins = [func, A, instance_a]

Now how do I get only instance_a out of plugins, assuming that I don't have a reference to the class instance A? Is it even possible?

Upvotes: 1

Views: 3686

Answers (2)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

If you want all instances, which are not class definitions themselves and not functions, then you can achieve this with:

import types
[x for x in plugins if type(x) == types.InstanceType]

However, I would consider this really an error prone solution as really you just find anything that somehow extends object and does not have a special type for that, like functions do. It would be best to define a superclass for all plugins implemented via class instances and filter on that:

[x for x in plugins if isinstance(x, Plugin)]

Upvotes: 4

Ben Hoff
Ben Hoff

Reputation: 1108

The easiest way to accomplish this that I can think of, in case someone runs into a similar problem is:

class A:
    pass

def func():
    pass

 a = A()
 plugins = [a, A, func]

 instance_plugins = [x for x in plugins if inspect.isclass(type(x)) and not type(x) == type]

Upvotes: 0

Related Questions