Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the use cases for Python's __new__?

Tags:

python

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 like str, int, unicode or tuple

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).

like image 295
JohnDoDo Avatar asked Oct 11 '12 08:10

JohnDoDo


1 Answers

Answering for myself, I've used it to

  • create a singleton pattern (though there are ways to do that without using __new__)
  • dynamically extend classes from external modules without actually editing the source
  • customize classes in a metaclass (though __call__ may also be used I think)
  • extend a the datetime.datetime class (which is immutable) to return the current time if instanciated without arguments and the result of calling strptime on the argument if called with a single string argument

You need __new__ when subclassing an immutable type if you want to alter the arguments used to construct the immutable, as I wanted in the datetime example, 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__.

like image 103
Lauritz V. Thaulow Avatar answered Oct 05 '22 22:10

Lauritz V. Thaulow