Mikael Lövqvist

A use case for __new__ in python

by Mikael Lövqvist on


Sometimes in python you may need to make sure an instance is of the right class without having to check it every time.
One could write a function that would check some condition and either call the class to create a new instance or simply return the one that was already given as the argument. But then you need that function and, on top of that, the actual class definition and that gets a bit ugly in the namespace.

By using __new__ we can put that condition in there together with the code we would put in __init__ to get around having to call __init__ with the same arguments as __new__ was called.

Note that this example is written for python 3

Useful links:

Mikael Lövqvist

Written by: Mikael Lövqvist