Alex Rivera | Logout

What's the use case for __new__ method to return an object of a different type than its first arg?

Asked 2012-04-18T09:01:16.590
9

The documentation implies that it's ok for __new__(cls, ...) to return an object of a type different than cls. It says in that case __init__() won't be called. It's not stated explicitly, but common sense or a simple test confirms that the resulting the object won't have type cls.

Why is this seemingly strange behavior allowed? What's the use case? It's clearly intentional.

Edit
Report

2 Answers

5

It can be useful when you create mock objects for unit testing.

You can change the __new__ method to return, in the certain cases, the the other object with the same interface, as original (for example simulating the original class instances' behaviour), without modifications to the rest of code.

answered 2012-04-18T09:05:30.223
4

I guess the Python folks just decided that there is no reason to enforce __new__(cls, ...) to return instances of cls. __new__ is a fairly advanced method, so the user probably knows what he's doing, and there could be some reasons to exploit this behavior.

They still have to do the check, though. During instance creation, __init__ should be called. This is only reasonable if the instance (returned from __new__) really is a cls. If __new__ returns something different, chances are that the object cannot handle the arguments that would be passed to __init__.

In the end, the addition of __new__ to the language left the developers with three choices:

  1. Enforce __new__(cls, ...) to return an instance of cls
  2. Always call __init__ on the instance returned by __new__, leaving it up to the user to ensure that the object can handle the arguments.
  3. Only call __init__ if the instance really is an instance of cls.

I guess that option 3 seemed most practical.

answered 2012-04-18T10:02:19.283

Your Answer