What is the best way to vary what class is instantiated based off parameters to an initialization function in Python? For example, for a quadtree, if the number of elements is below a certain threshold, you want to return a leaf rather than a branch. Another example would be a graph which can either be backed by a adjacency matrix or list depending on what data it is initialized with.
The most obvious way I can think to do this is with a factory function that determines which subclass of the class in question should be initialized. Is there a better, more pythonic
way of going about this?
In one particularly tricky instance of this problem, I had a data structure that could be backed by any kind of sequence or dict type. The backing/subclass used depended on the type of the data that it was fed. In a statically typed language, I could simply have used function overloading, but in Python I was left to either explicitly call isinstance, or use a bunch of “try…catch AttributeError”s. Both of these seem like quite bad practice. Using the factory function solution above, I don’t see a clean way to do it though. (I realize this is sort of a different issue, but it is a big case that got me trying to figure this out.)
You can use
__new__, but a factory function is the nice pythonic way to go.