`__new__`
__new__ is the real constructor: a static method that allocates (or reuses) an instance and returns it. __init__ then initialises that instance. Most classes never override __new__.
Detailed Explanation
Order(...) is two steps. First Order.__new__(Order, ...) produces an object. If that object is an instance of Order, Order.__init__ is called on it. If __new__ returns something else — another type, or an existing instance — __init__ is not called.
The default object.__new__(cls) allocates an empty instance of cls. You need a custom __new__ in a short list of situations: subclassing an immutable builtin (int, str, tuple) whose value is fixed at allocation time; implementing a singleton or interned cache; returning a pre-existing object from a pool; or writing a metaclass.
For an immutable subclass, __init__ is too late. str is already complete when __new__ returns. You compute the value, call super().__new__(cls, value), and return that.
For a singleton, __new__ looks up a class attribute and returns it if it exists, otherwise it allocates and stores it. __init__ will run on every Class() call if the returned object is an instance of the class, which is why singletons often set a flag or move setup into __new__. The singleton entry covers the design; __new__ is only the mechanism.
__new__ is implicitly a static method. Its first argument is the class, conventionally cls, not an instance. You must return an object. Returning None makes the call Class() produce None and skip __init__.
Do not use __new__ for ordinary attribute setup. It is harder to read, easy to get super().__new__ wrong, and interacts badly with __init__ running twice. Write __init__ unless you have one of the reasons above.
Code Examples
class Sku(str):
"""Immutable SKU: the value must be set in __new__, not __init__."""
def __new__(cls, raw: str) -> "Sku":
cleaned = raw.strip().upper()
return super().__new__(cls, cleaned)
print(Sku(" a-1 ")) # A-1
print(isinstance(Sku("a-1"), str)) # Trueclass Sentinel:
_instance = None
def __new__(cls) -> "Sentinel":
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
print(Sentinel() is Sentinel()) # Trueclass SkipInit:
def __new__(cls, value: int):
return value # not a SkipInit, so __init__ is skipped
def __init__(self, value: int):
raise RuntimeError("not called")
print(SkipInit(7)) # 7Common Gotchas
Forgetting to return `super().__new__(cls)`
returning `None` or forgetting `return` makes `Class()` mysteriously produce `None`.
`__init__` still runs on every call if you return an instance of the class
a singleton's `__init__` will reset state unless you guard it. Prefer doing one-time setup in `__new__` or a flag.
Immutable builtins ignore later attribute assignment
subclass `str` in `__new__`, not by setting `self.something` afterwards for the payload.
`__new__` receives the same extra arguments as `__init__`
they are passed through. Accept `*args, **kwargs` if you only care about `cls`.