OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Pickling subclass does not save new instance attribute

  • Thread starter Thread starter Brian
  • Start date Start date
B

Brian

Guest
Pickling a subclass that adds a new attribute doesn't seem to include the new attribute. For example:

Code:
import requests
import pickle

class MySession(requests.Session):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.details = False

data = MySession()
file = "/tmp/pickle"

with open(file, "wb") as f:
    from pprint import pprint
    print(f"Saving session {data} to {file} with {data.details}")
    pprint(data.__dict__)
    pickle.dump(data, f)
print("Validating")
with open(file, "rb") as f:
    newdata = pickle.load(f)
    pprint(newdata.__dict__)
    print(data.details)
    print(newdata.details)

produces the following exception:

Code:
Saving session <__main__.MySession object at 0x7f0976cb9400> to /tmp/pickle with False
{'adapters': OrderedDict([('https://',
                           <requests.adapters.HTTPAdapter object at 0x7f0975dca4e0>),
                          ('http://',
                           <requests.adapters.HTTPAdapter object at 0x7f0976be9ca0>)]),
 'auth': None,
 'cert': None,
 'cookies': <RequestsCookieJar[]>,
 'details': False,
 'headers': {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'},
 'hooks': {'response': []},
 'max_redirects': 30,
 'params': {},
 'proxies': {},
 'stream': False,
 'trust_env': True,
 'verify': True}
Validating
{'adapters': OrderedDict([('https://',
                           <requests.adapters.HTTPAdapter object at 0x7f09759c1010>),
                          ('http://',
                           <requests.adapters.HTTPAdapter object at 0x7f0975a4e960>)]),
 'auth': None,
 'cert': None,
 'cookies': <RequestsCookieJar[]>,
 'headers': {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'},
 'hooks': {'response': []},
 'max_redirects': 30,
 'params': {},
 'proxies': {},
 'stream': False,
 'trust_env': True,
 'verify': True}
False
Traceback (most recent call last):
  File "/tmp/repro.py", line 22, in <module>
    print(newdata.details)
          ^^^^^^^^^^^^^^^
AttributeError: 'MySession' object has no attribute 'details'

The details attribute of MySession didn't get saved in the pickle file. But why?

Disregard below this line: Now I am just going to ramble because SO thinks my post contains too much code and not enough details, but when a picture is worth a thousand words, why do we need to add 10,000 words to a pretty self explanatory picture?
<p>Pickling a subclass that adds a new attribute doesn't seem to include the new attribute. For example:</p>
<pre class="lang-py prettyprint-override"><code>import requests
import pickle

class MySession(requests.Session):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.details = False

data = MySession()
file = "/tmp/pickle"

with open(file, "wb") as f:
from pprint import pprint
print(f"Saving session {data} to {file} with {data.details}")
pprint(data.__dict__)
pickle.dump(data, f)
print("Validating")
with open(file, "rb") as f:
newdata = pickle.load(f)
pprint(newdata.__dict__)
print(data.details)
print(newdata.details)
</code></pre>
<p>produces the following exception:</p>
<pre><code>Saving session <__main__.MySession object at 0x7f0976cb9400> to /tmp/pickle with False
{'adapters': OrderedDict([('https://',
<requests.adapters.HTTPAdapter object at 0x7f0975dca4e0>),
('http://',
<requests.adapters.HTTPAdapter object at 0x7f0976be9ca0>)]),
'auth': None,
'cert': None,
'cookies': <RequestsCookieJar[]>,
'details': False,
'headers': {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'},
'hooks': {'response': []},
'max_redirects': 30,
'params': {},
'proxies': {},
'stream': False,
'trust_env': True,
'verify': True}
Validating
{'adapters': OrderedDict([('https://',
<requests.adapters.HTTPAdapter object at 0x7f09759c1010>),
('http://',
<requests.adapters.HTTPAdapter object at 0x7f0975a4e960>)]),
'auth': None,
'cert': None,
'cookies': <RequestsCookieJar[]>,
'headers': {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'},
'hooks': {'response': []},
'max_redirects': 30,
'params': {},
'proxies': {},
'stream': False,
'trust_env': True,
'verify': True}
False
Traceback (most recent call last):
File "/tmp/repro.py", line 22, in <module>
print(newdata.details)
^^^^^^^^^^^^^^^
AttributeError: 'MySession' object has no attribute 'details'
</code></pre>
<p>The <code>details</code> attribute of <code>MySession</code> didn't get saved in the pickle file. But why?</p>
<p>Disregard below this line:
Now I am just going to ramble because SO thinks my post contains too much code and not enough details, but when a picture is worth a thousand words, why do we need to add 10,000 words to a pretty self explanatory picture?</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Ads by Eonads
Top