Search code examples
pythonmetaclassdynamic-class-creation

Python __new__ without calling another class's version of __new__?


What is an example of using __new__ in Python such that within the body of __new__ you do not return the result of calling some other (base, meta, or otherwise) class's version of __new__, but you do return an allocated instance of the intended class so that __init__ will be invoked?

I'm guessing this is (and should be) very rare, but I'm curious if there is an example of this use case. I tried searching around for the Python source of tuple's implementation of __new__ and also for type's implementation, but it did not seem like this is quick and easy to find online.


Solution

  • You can't, that's not something you can do on the Python side of things. A no-op __new__ method would call object.__new__(cls), which returns a bare instance of class cls.

    >>> class A:
    ...     def __new__(cls):
    ...         return object.__new__(cls)
    ... 
    >>> A()
    <__main__.A object at 0x7f9e951577d0>