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@python
components: Documentation
messages: 288088
nosy: docs@python, max
priority: normal
severity: normal
status: open
title: __new__ / __init__ calls during unpickling not documented correctly
versions: Python 3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue29597>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to