Sub topic 3
Creating objects: __new__ and __init__
This chapter assumes you can define classes and write __init__ methods. It also assumes you know that isinstance checks a value's type and that str, int and tuple are immutable. By the end you will know what Python does when you write Cls(...). You will also know when __init__ is not enough and __new__ is needed.
Construction takes two steps
Most classes only define __init__, so it is easy to think __init__ creates the object. It does not. Calling a class runs two steps:
__new__(cls, *args, **kwargs)creates and returns the instance.__init__(self, *args, **kwargs)sets up that instance, but only if step 1 returned an instance ofcls.
Both steps receive the same arguments you passed to the class.
The following class prints a line in each step so you can see the order:
class Trace:
def __new__(cls, *args, **kwargs):
print('__new__', args)
return super().__new__(cls)
def __init__(self, name):
print('__init__', name)
self.name = name
t = Trace('a')
# __new__ ('a',)
# __init__ a__new__ is a static method that Python treats specially, so you do not need the @staticmethod decorator. Its first parameter is the class, not an instance, because no instance exists yet.
Comparing the two methods
| Row | `__new__` | `__init__` |
|---|---|---|
| First parameter | `cls` (the class) | `self` (the new instance) |
| Job | Create and return the object | Fill in the object's attributes |
| Return value | The instance (any object is allowed) | Must be `None` |
| Runs when | Always, first | Only if `__new__` returned an instance of `cls` |
| Typical use | Immutable types, caching, custom allocation | Almost every class |
If __init__ returns anything other than None, Python raises TypeError. A stray return self in __init__ is therefore an error.
Calling the parent's __new__
The default __new__ comes from object. To create the instance you call the parent's version and pass only cls:
def __new__(cls, *args, **kwargs):
return super().__new__(cls)Do not forward *args to object.__new__. When a class overrides __new__, object.__new__ raises TypeError if it receives extra arguments. Your __init__ still receives the arguments, because Python passes them to both methods.
Returning something that is not an instance
Python only calls __init__ when __new__ returns an instance of cls. If it returns anything else, __init__ is skipped and the caller gets that other object:
class Weird:
def __new__(cls):
return 42
def __init__(self):
print('never printed')
print(Weird()) # 42This is legal but rarely a good idea, because Weird() no longer gives you a Weird. Treat it as a way to understand the mechanism. It is not a design to copy.
Why immutable types need __new__
By the time __init__ runs, the object already exists. For a mutable object that is fine, because you can change it afterwards. For an immutable type such as str, int or tuple, the value is fixed when the object is created. Assigning a different value in __init__ does not change it.
To customize the value of an immutable subclass, change the arguments in __new__ before calling the parent:
class UpperStr(str):
def __new__(cls, value):
return super().__new__(cls, str(value).upper())
u = UpperStr('hello')
print(u) # HELLO
print(isinstance(u, str)) # True
print(u + ' world') # HELLO worldHere super().__new__(cls, ...) is str.__new__, so it accepts the string value, unlike object.__new__. The same approach works for subclasses of int, float and tuple. For example, you can validate or normalize the number before it is stored.
Controlling which instances exist
Because __new__ decides what to return, it can hand back an existing object instead of building a new one. A cache of shared instances is sometimes called the flyweight pattern:
class Color:
_cache = {}
def __new__(cls, name):
try:
return cls._cache[name]
except KeyError:
self = super().__new__(cls)
self.name = name
cls._cache[name] = self
return self
print(Color('red') is Color('red')) # True
print(Color('red') is Color('blue')) # FalseThe class has no __init__, and this is deliberate. The next section shows why.
Pitfall: __init__ runs again on a reused object
Here is a singleton that looks correct and behaves surprisingly:
class Config:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, path):
print('init', path)
self.path = path
a = Config('a.ini') # init a.ini
b = Config('b.ini') # init b.ini
print(a is b) # True
print(a.path) # b.iniBoth names point to the same object, but the second call overwrote path. There are three common fixes:
- Do all setup in
__new__and define no__init__, asColordoes. - Guard
__init__with a flag, for exampleif hasattr(self, 'path'): return. - Use a module-level variable or a factory function instead of a singleton class. This is usually the simplest choice.
Pitfall: some paths never call __init__
__new__ and __init__ are not the only ways to get an instance. copy.copy and pickle rebuild objects without calling __init__:
import copy
class Noisy:
def __init__(self):
print('init')
self.x = 1
n = Noisy() # init
m = copy.copy(n) # prints nothing
print(m.x) # 1The copy still has x, because the copy machinery copies the instance's attributes. An invariant that exists only as a side effect of __init__, such as registering the object in a global list, is therefore not guaranteed for copied or unpickled objects. If this matters, implement __copy__, __reduce__ or __setstate__ to maintain it.
Choosing a tool
Use __init__ for almost everything. Reach for __new__ only when one of these applies:
- You subclass an immutable built-in type and must change the value.
- You need to return a cached or shared instance.
- You need to choose the class that gets created. In that case a
@classmethodfactory or a plain function is usually clearer.
If a classmethod such as Config.from_file(path) expresses what you want, prefer it. It is explicit, easy to test, and avoids the repeated-__init__ problem. Overriding __new__ surprises readers, so keep the override small and say why it is there.
Exercise
A class Meters(float) defines def __init__(self, value): self = abs(value) to store absolute values. Why does Meters(-3) still show -3.0, and how do you fix it?
Show answer
Python creates the float with the value -3 in __new__ before __init__ runs, and a float cannot change after creation. Reassigning the local name self in __init__ only rebinds that variable and does not change the object. Fix it by overriding __new__: def __new__(cls, value): return super().__new__(cls, abs(value)).
Exercise
You write a class whose __new__ returns a cached instance and whose __init__ sets self.items = []. What goes wrong when you call the class twice, and what are two ways to avoid it?
Show answer
Each call runs __init__ on the same shared object, so self.items is reset to an empty list and data added through the first reference disappears. Avoid it by dropping __init__ and doing the setup in __new__ when the instance is first created, or by guarding __init__ so it runs the setup only once.