Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. __init__ vs __new__

Python · Language Internals Interviewers Still Ask

__init__ vs __new__

Mediumpython-63
oopnewinitsingletonimmutable

Question

What is the difference between __init__ and __new__?

Solution

__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, str or int cannot 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._instance

Other 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__.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext