cPickle error when caching data

Peter Otten __peter__ at web.de
Tue Aug 3 17:01:05 CEST 2010

Benedict Verheyen wrote:

> i get the following error when trying to set data in the cache of a django
> application. The error is however a python error as it involves pickling
> and i can reproduce it in a shell.
> The error i get is this:
> cPickle.PicklingError: Can't pickle <class 'management.views.Stats'>:
> attribute lookup management.views.Stats failed
> Stats is a class i use to hold a couple of values, a string (user) and a
> number (calls), that are then used in a template. These are pickable,
> right? The data i want to pickle is the return value of this function:
> def calc_stats_topcallers():
>     stats_all = {}
>     # cPickle doesn't like this class
>     class Stats(object):
>         def __init__(self):
>             self.calls = None
>             self.user = None

You can only pickle instances of classes that are reachable by the import 
system as only the qualified name of the class is stored, not the bytecode 
to generate it. Move your class out of the function into the global module 
scope and you should be OK.


More information about the Python-list mailing list