_va2jw
Last Updated: February 25, 2016
·
253
· tonnydourado

Order matters

Just found out order matters when using multiple inheritance on python classes. I guess I should expect that, I even remember reading this on the docs, but I thought "Hey, lets share a tip on coderwall, maybe that way I wont forget it later and got bitten in the ass by weird bugs".

So, a little example (from actual code I am working in)

class Service(object):
    def all(self):
        return self.__model__.query.all()

class FilterInactiveMixin(object):
    def all(self):
        return self.__model__.query.filter_by(active=True)

class UsersServiceThatWorks(FilterInactiveMixin, Service):
    pass

class UsersServiceThatDoesnt(Service, FilterInactiveMixin):
    pass

So, basically, when calling the all method on a UserServiceThatWorks instance, the method from FilterInactiveMixin will be called. If you invert the order, it never gets called, and you will probably get weird behaviour.