How to set up a python class inheritance so that a class and an instance present the same interface?

Viewed 42

I've got two classes, which do different things, but present some of the same interface methods. The challenge is that one is used as a class and the other is designed to used as an instance.

Right now this looks something like:

class ClassDesignedToBeUsedAsClass():
    @classmethod
    def match(cls, **kwargs):
        # Do some stuff with cls
        return result


class ClassDesignedToBeUsedAsInstance():
    def match(self, **kwargs):
        # Do some stuff with self
        return result

# NB: One is instantiated, and the other isn't
thing1 = ClassDesignedToBeUsedAsClass
thing2 = ClassDesignedToBeUsedAsInstance()


for thing in [thing1, thing2]:
    # At this stage we can treat both of them the same
    thing.match(**kwargs)

Whether or not this is a good idea is a separate question, and a design decision made a long time ago and very deep in the codebase.

The current setup leads to some duplication of code between the two classes, and I'd love to move that code out into a common ancestor or mixin. This has the benefit of more "Don't repeat yourself", but also the potential of doing better type checking a validation using mypy or similar.

What I don't know is how to do inheritance to set up common methods (or at least method stubs of methods) which end up as class methods in one child and instance methods in the other. Is that possible? Is class inheritance even a good idea here?

0 Answers
Related