Before __init__ Runs: How __new__ Creates Python Objects
This article explains how __new__ creates a Python object before __init__ configures it, how it subclasses immutable types and returns cached instances, and which errors it causes in singletons, pickling and argument forwarding.
Calling a class in Python is usually described as calling its constructor, __init__, but by the time __init__ runs the object already exists, and __init__ only fills in its attributes. The present article examines the method that creates the object in the first place, __new__. Crafting systems in many games provide an appropriate image: an item is first forged from a material, and only afterwards can it be enchanted, so an item whose material cannot change must be forged from the right one, because no enchantment will alter it later. This means that __new__ creates and returns the instance, while __init__ receives that instance and configures it, and that for immutable types such as str, int or tuple the value must be decided in __new__, because there is nothing left to change in __init__. The analogy, however, stops at this point, because both steps run automatically within a single call, and __new__ may even return an object that already existed. The article traces the order of the two calls, subclasses immutable types, shows how __new__ can return existing instances, and analyses the errors that make its use delicate. Deciding what object a call to a class produces, before any initializer sees it, is the secret weapon of __new__.
The Order of Creation
When a class is called, Python first calls its __new__ with the class and all the arguments, and then, if the result is an instance of that class, calls __init__ on the result with the same arguments. The data model documentation states the condition explicitly: if __new__ returns something that is not an instance of the class, __init__ is not called at all. The method __new__ is a static method that Python treats specially, so it needs no decorator, and it normally delegates the actual allocation to super().__new__(cls).
class Traced:
def __new__(cls, value):
print(f"__new__ receives {value!r}")
return super().__new__(cls)
def __init__(self, value):
print(f"__init__ receives {value!r}")
self.value = value
item = Traced(42)
# Output: __new__ receives 42
# Output: __init__ receives 42
class Parser:
def __new__(cls, text):
if not text:
return None
return super().__new__(cls)
def __init__(self, text):
self.text = text
print(Parser(""), type(Parser("x")).__name__) # Output: None Parser
The trace confirms that both methods receive the arguments of the call, in that order. The parser returns None for empty text, so its __init__ never runs for that call; the technique is legal but surprising, since a call to a class normally returns an instance of it, and a class method or a function usually expresses such a rule more clearly.
Subclassing Immutable Types
The most important use of __new__ is the creation of subclasses of immutable built-in types, whose value is fixed at creation. A temperature that refuses values below absolute zero, or a point stored as a tuple of two coordinates, must validate or build its value in __new__, because by the time __init__ runs the float or the tuple can no longer change. A subclass whose __new__ takes different arguments from its base type also needs __getnewargs__, because pickle and copy recreate the object by calling __new__ with the arguments that this method returns.
import pickle
class Temperature(float):
def __new__(cls, celsius):
if celsius < -273.15:
raise ValueError("below absolute zero")
return super().__new__(cls, celsius)
print(Temperature(21.5) + 1) # Output: 22.5
try:
Temperature(-300)
except ValueError as error:
print(error) # Output: below absolute zero
class Point(tuple):
def __new__(cls, x, y):
return super().__new__(cls, (x, y))
def __getnewargs__(self):
return tuple(self)
@property
def x(self):
return self[0]
restored = pickle.loads(pickle.dumps(Point(3, 4)))
print(restored, restored.x, type(restored).__name__) # Output: (3, 4) 3 Point
The temperature behaves as an ordinary float in arithmetic, and the validation runs once, at creation, so no invalid instance can exist. Without __getnewargs__, the point would be pickled correctly but could not be restored, because pickle would call Point.__new__ with a single tuple instead of two coordinates; the same error appears with copy.copy.
Returning Existing Instances
Because __new__ decides which object a call produces, it can return an object created earlier instead of a new one, which is the basis of caches of instances and of singletons. Caching immutable instances in a weakref.WeakValueDictionary, as described in the article devoted to the Flyweight pattern, lets equal values share one object without keeping unused ones alive. A singleton is the extreme case, a cache of size one; the alternative examined in the article devoted to the Borg pattern shares the state instead of the object. Both variants share a hazard that is easy to overlook, examined in the following section: __init__ still runs on every call.
Pitfalls of new
The method controls a step that most classes never customize, so its errors usually come from forgetting how it interacts with __init__ and with the machinery that recreates objects. Six pitfalls are distinguished, which are the following:
- Re-initialized singletons. When
__new__returns the existing instance, Python still calls__init__, which overwrites the state with the arguments of the latest call. - Forwarding arguments to
object.__new__. Passing the call arguments tosuper().__new__(cls, *args)raisesTypeErrorwhen the base isobject, which accepts only the class. - Changed signatures and
pickle. A subclass of an immutable type whose__new__takes different arguments cannot be unpickled or copied without__getnewargs__. - Returning another type. A
__new__that returns an object of another class silently skips__init__, which surprises readers who expect an instance. - Forgetting to return. A
__new__without areturnstatement producesNone, and the call to the class returnsNone. __new__where a class method suffices. Alternative constructors, such as building an object from a file or a string, are clearer as class methods that call the class normally.
The first two pitfalls are reproduced in the following example.
class Connection:
_instance = None
def __new__(cls, url):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, url):
self.url = url
first = Connection("db://primary")
second = Connection("db://replica")
print(first is second, first.url) # Output: True db://replica
class Forwarding:
def __new__(cls, *args):
return super().__new__(cls, *args)
def __init__(self, x):
self.x = x
try:
Forwarding(1)
except TypeError as error:
print(error) # Output: object.__new__() takes exactly one argument (the type to instantiate)
The singleton returns the same object for both calls, but the second call ran __init__ again and replaced the address of the primary database with that of the replica. A singleton built on __new__ must therefore guard its initialization or move it into __new__, and a simpler design, a module-level instance or a metaclass whose __call__ skips __init__, as described in the article devoted to metaclasses, avoids the problem altogether. The second class fails because it forwards its argument to object.__new__, which accepts only the class once __new__ has been overridden.
Choosing Where to Customize Creation
Consequently, __new__ is the right place only when the identity or the immutable value of the object must be decided before it exists, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Setting attributes of a new object | __init__ |
Subclassing str, int, float or tuple |
__new__, plus __getnewargs__ if the signature changes |
| Validating an immutable value | __new__ |
| Reusing equal immutable instances | __new__ with a weak-value cache |
| A single shared object | A module-level instance, or a metaclass __call__ |
| Alternative ways to build an object | Class methods that call the class |
| Customizing how classes themselves are created | A metaclass __new__ or __init_subclass__ |
Conclusion
It is concluded that __new__ creates the object and __init__ only initializes it, that Python calls __init__ only when __new__ returns an instance of the class, and that __new__ is indispensable for subclasses of immutable types and useful for returning cached instances. This magic depends on remembering that __init__ runs again for every returned instance, on calling object.__new__ with the class alone and on providing __getnewargs__ when the signature changes. Creating a unique object whose only purpose is to be recognized by its identity, such as a marker for a missing value, is the purpose of the Sentinel pattern, which is developed in a future article of this series.