Author pekka.klarck
Recipients pablogsal, pekka.klarck, xtreak
Date 2018-10-16.08:38:32
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
My use case was implementing conversion of strings to different objects based on type information got from function arguments. Initially I had a converter class with methods for each conversion (e.g. `_convert_bool`, `_convert_int`) but this class got so big that I decided to split each converter into a separate class (e.g. `BooleanConverter`, `IntegerConverter`) with a common base class. The base class also has a `converter_for` classmethod that is a factory that returns a concrete converter for a certain type.

For the factory to be able to return a correct converter, it obviously needs to know what converters exist and what types they handle. My first idea was to simply go through `cls.__subclasses__()` and return the first one that handles the specified type, but because order matters for us this doesn't work. The reason order matters is that we handle both Boolean and integer types, and `bool` being a subclass of `int` means we need to handle the former first.

Because I couldn't use `cls.__subclasses__()`, I needed to implement a custom way for the converters to register themselves. That wasn't particularly complicated but some extra work anyway.

The code I wrote happens to be open source and visible at [1] if you are interested to look it more closely. The `@TypeConverter.register` stuff could have been avoided is `cls.__subclasses__()` were ordered. It could also be removed once we drop Python 3.5 support *if* order is guaranteed to be preserved going forward.

Date User Action Args
2018-10-16 08:38:33pekka.klarcksetrecipients: + pekka.klarck, pablogsal, xtreak
2018-10-16 08:38:33pekka.klarcksetmessageid: <>
2018-10-16 08:38:33pekka.klarcklinkissue34805 messages
2018-10-16 08:38:32pekka.klarckcreate