This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: __new__ / __init__ calls during unpickling not documented correctly
Type: Stage: resolved
Components: Documentation Versions: Python 3.6
process
Status: closed Resolution: duplicate
Dependencies: Superseder: pickle documentation says that unpickling may not call __new__
View: 27635
Assigned To: docs@python Nosy List: docs@python, max, serhiy.storchaka
Priority: normal Keywords:

Created on 2017-02-18 20:31 by max, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg288088 - (view) Author: Max (max) * Date: 2017-02-18 20:31
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__
msg288090 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-02-18 20:47
This is a duplicate of issue27635.
History
Date User Action Args
2022-04-11 14:58:43adminsetgithub: 73783
2017-02-18 20:47:07serhiy.storchakasetstatus: open -> closed

superseder: pickle documentation says that unpickling may not call __new__

nosy: + serhiy.storchaka
messages: + msg288090
resolution: duplicate
stage: resolved
2017-02-18 20:31:11maxcreate