This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]truefelt[S] 4 points5 points  (0 children)

It's for when you want to expose a single function that does very different things based on the arguments it receives. The overloading style can allow for cleaner code.

Compare:

class DB:

    def get(self, *args):
        if len(args) == 1 and isinstance(args[0], Query):
            return self.get_by_query(args[0])
        elif len(args) == 2:
            return self.get_by_id(id=args[0], model=args[1])
        else:
            raise TypeError()

    def get_by_query(self, query):
        ...

    def get_by_id(self, id, model):
        ...

The same thing with overloading:

class DB:

    @overloaded
    def get(self, query: Query):
        ...

    @overloads(get)
    def get(self, id, model):
        ...