Python pickle crash when trying to return default value in __getattr__

2024/9/23 14:33:33

I have a dictionary like class that I use to store some values as attributes. I recently added some logic(__getattr__) to return None if an attribute doesn't exist. As soon as I did this pickle crashed, and I wanted some insight into why?

Test Code:

import cPickle
class DictionaryLike(object):def __init__(self, **kwargs):self.__dict__.update(kwargs)def __iter__(self):return iter(self.__dict__)def __getitem__(self, key):if(self.__dict__.has_key(key)):return self.__dict__[key]else:return None''' This is the culprit...'''    def __getattr__(self, key):print 'Retreiving Value ' , keyreturn self.__getitem__(key)class SomeClass(object):def __init__(self, kwargs={}):self.args = DictionaryLike(**kwargs)someClass = SomeClass()
content = cPickle.dumps(someClass,-1)
print content

Result:

Retreiving Value  __getnewargs__
Traceback (most recent call last):File <<file>> line 29, in <module>content = cPickle.dumps(someClass,-1)
TypeError: 'NoneType' object is not callable`

Did I do something stupid? I had read a post that deepcopy() might require that I throw an exception if a key doesn't exist? If this is the case is there any easy way to achieve what I want without throwing an exception?

End result is that if some calls

someClass.args.i_dont_exist

I want it to return None.

Answer

Implementing __getattr__ is a bit tricky, since it is called for every non-existing attribute. In your case, the pickle module tests your class for the __getnewargs__ special method and receives None, which is obviously not callable.

You might want to alter __getattr__ to call the base implementation for magic names:

def __getattr__(self, key):if key.startswith('__') and key.endswith('__'):return super(DictionaryLike, self).__getattr__(key)return self.__getitem__(key)

I usually pass through all names starting with an underscore, so that I can sidestep the magic for internal symbols.

https://en.xdnf.cn/q/71816.html

Related Q&A

How to download google source code for android

As you know, there is a list of several hundred projects in https://android.googlesource.com/. Id like to download them all in windows machine. According to Googles document,To install, initialize, and…

Compute on pandas dataframe concurrently

Is it feasible to do multiple group-wise calculation in dataframe in pandas concurrently and get those results back? So, Id like to compute the following sets of dataframe and get those results one-by…

How do I go about writing a program to send and receive sms using python?

I have looked all over the net for a good library to use in sending and receiving smss using python but all in vain!Are there GSM libraries for python out there?

Persist Completed Pipeline in Luigi Visualiser

Im starting to port a nightly data pipeline from a visual ETL tool to Luigi, and I really enjoy that there is a visualiser to see the status of jobs. However, Ive noticed that a few minutes after the l…

How to assign python requests sessions for single processes in multiprocessing pool?

Considering the following code example:import multiprocessing import requestssession = requests.Session() data_to_be_processed = [...]def process(arg):# do stuff with arg and get urlresponse = session.…

Missing values in Pandas Pivot table?

I have a data set that looks like the following:student question answer number Bob How many donuts in a dozen? A 1 Sally How many donuts in a do…

Selecting Element followed by text with Selenium WebDriver

I am using Selenium WebDriver and the Python bindings to automate some monotonous WordPress tasks, and it has been pretty straightforward up until this point. I am trying to select a checkbox, but the …

AttributeError: module keras.backend has no attribute image_dim_ordering

I tried to execute some tutorial transfer learning project. But Ive got attribute error.I checked my tensorflow and keras version.tensorflow : 1.14.0 keras : 2.2.5and python 3.6.9 version.the code is h…

Python Interpreter String Pooling Optimization [duplicate]

This question already has answers here:What determines which strings are interned and when? [duplicate](3 answers)Closed 6 years ago.After seeing this question and its duplicate a question still remai…

Flattening an array in pandas

One of the columns in DataFrame is an array. How do I flatten it? column1 column2 column3 var1 var11 [1, 2, 3, 4] var2 var22 [1, 2, 3, 4, -2, 12] var3 var33 [1, 2, 3, 4, 33, 544]Afte…