Python and multiple constructors

One thing I missed when switching from Java to Python was multiple constructors. Python does not support them (directly), but there a may other approaches that work very similar (maybe even better).

Problem

Let’s say we are building a client to query remote service (some aggregation service). We want to pass the aggregator.

To make code more fluent and giving it more robustness for integrating into other solutions, we have multiple options to create an aggregator.

The query.aggregator will create a new instance of Aggregator and pass it to the request.

(Possible) solution

Python has a great feature of passing args and kwargs. We can create a constructor

then in the constructor we check and parse args and kwargs. This solution works, but it has many problems:

  1. No indication what is required and what not
    This is most important for autocompletion. When I want to create a new instance of the class Aggregator, I want to know what is required. With current constructor, this is really hard.
  2. Complexity and combinations
    There are many combinations how to initialize a new instance by passing different arguments.

    This is absolutely weird and hard to read.

Better solution

Python has an option to decorate a method with @classmethod. We can define custom methods that work as multiple constructors. For example, we can create a method from_arguments.

We use it as Aggregator.from_arguments(args). The validation of the parameters (if value an int) is done in the constructor.

The from_arguments method just parses the arguments and creates a new instance of the Aggregator. We could add a validation (if list has at least 2 items, if str is in correct format, if dict has all the required elements, …).

Hi, I'm Erol
Senior Fullstack Developer

I'm available for hire. So if you need help, send me an email.