__new__ creates the object and returns it. __init__ then sets it up. Almost all the time you only write __init__, and __new__ matters in a few special cases.
The order of calls
When you write Order(5), Python does roughly this:
obj = Order.__new__(Order, 5) # 1. allocate and return a new instance
if isinstance(obj, Order):
obj.__init__(5) # 2. initialise it__new__ is a static method (Python treats it specially, so you do not need the decorator) that receives the class (cls) as its first argument. It returns the instance. __init__ receives the instance (self), returns nothing, and fills in attributes.
When __new__ is needed
- Subclassing immutable types. A
tuple,strorintcannot be changed after creation, so the value must be decided in__new__:
class Upper(str):
def __new__(cls, value):
return super().__new__(cls, value.upper())
Upper("abc") # 'ABC'__init__ would be too late, since the string already exists.
- Singletons: return the same instance each time.
class Config:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instanceOther uses of __new__:
- Object caching or pooling, and metaclass-level tricks.
A subtle point
If __new__ returns an object that is not an instance of the class, __init__ is not called. And if it returns an existing instance (as in the singleton), __init__ runs again every time you call the class, so keep initialisation idempotent or guard it.
How it relates to day-to-day work
You will rarely write either beyond a simple __init__. Dataclasses and Pydantic generate __init__ for you. In data engineering code, a module-level object or a function usually does the job of a singleton more simply.
How to answer
State the roles (create versus initialise), give the order, and name one use for each of the two real cases. Then say honestly that you almost never need __new__.