[docs] [issue29597] __new__ / __init__ calls during unpickling not documented correctly
Max
report at bugs.python.org
Sat Feb 18 15:31:11 EST 2017
New submission from Max:
According to the [docs](https://docs.python.org/3/library/pickle.html#pickling-class-instances):
> Note: At unpickling time, some methods like `__getattr__()`, `__getattribute__()`, or `__setattr__()` may be called upon the instance. In case those methods rely on some internal invariant being true, the type should implement `__getnewargs__()` or `__getnewargs_ex__()` to establish such an invariant; otherwise, neither `__new__()` nor `__init__()` will be called.
It seems, however, that this note is incorrect. First, `__new__` is called even if `__getnewargs__` isn't implemented. Second, `__init__` is not called even if it is (while the note didn't say that `__init__` would be called when `__getnewargs__` is defined, the wording does seem to imply it).
class A:
def __new__(cls, *args):
print('__new__ called with', args)
return object.__new__(cls)
def __init__(self, *args):
print('__init__ called with', args)
self.args = args
def __getnewargs__(self):
print('called')
return ()
a = A(1)
s = pickle.dumps(a)
a = pickle.loads(s) # __new__ called, not __init__
delattr(A, '__getnewargs__')
a = A(1)
s = pickle.dumps(a)
a = pickle.loads(s) # __new__ called, not __init__
----------
assignee: docs at python
components: Documentation
messages: 288088
nosy: docs at python, max
priority: normal
severity: normal
status: open
title: __new__ / __init__ calls during unpickling not documented correctly
versions: Python 3.6
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue29597>
_______________________________________
More information about the docs
mailing list