I understand what __new__ does (and how it’s different from __init__) so I’m not interested in definitions, I’m interested in when and how to use __new__.
The documentation says:
In general, you shouldn’t need to override
__new__unless you’re subclassing an immutable type likestr,int,unicodeortuple
But I can’t think of other cases to use __new__ or how to use it correctly (for example when subclassing an immutable type or why it’s needed in this case).
So, when, why and how do you need to use __new__?
I’m interested in the use cases, not what it does (I know what it does).
Answering for myself, I’ve used it to
__new__)__call__may also be used I think)datetime.datetimeclass (which is immutable) to return the current time if instanciated without arguments and the result of callingstrptimeon the argument if called with a single string argumentYou need
__new__when subclassing an immutable type if you want to alter the arguments used to construct the immutable, as I wanted in thedatetimeexample, or if you don’t want to call the parent__new__at all but return an instance created another way or even of an entirely different type. By the time you’re in__init__it’s too late to alter the object in any way, so you need to do it in__new__.