python: pickle misbehaving in django shell as opposed to python shell?
Question: As an additional question stemming from [my previous
question](http://stackoverflow.com/questions/24240001/pickle-cant-store-an-
object-in-django-locmem-cache-during-tests/24241848#24241848) it turns out
that pickle behaves differently in django shell compared to python shell...

this script:

    
    
    import pickle
    
    class TestObj(object): pass
    testobj = TestObj()
    pickled = pickle.dumps(testobj, pickle.HIGHEST_PROTOCOL)
    

will work fine in python shell, but in django shell will raise a `PickleError`
along the lines of `PicklingError: Can't pickle <class 'TestObj'>: attribute
lookup __builtin__.TestObj failed`

Is anyone able to explain the issue here? and if possible, link it back to my
previous question?


Answer: `pickle` will make sure it can re-import a class, as only the data on the
instance itself is pickled, plus the import location of the class. As such,
`pickle` looks for the `__module__` attribute on the class to determine where
it came from.

It appears the Django interactive environment does not _set_ this `__module__`
attribute; as a result `TestObj.__module__` is inherited from the `object`
base class instead, and that's `__builtin__`. Perhaps no `__name__` global is
set. As a result, the `pickle` module ends up looking in the wrong place for
your class. There is no `__builtin__.TestObj` after all.

From the comments, I gather that you are trying to store mocked objects in the
Django cache. That won't work, as [mock objects are not
pickleable](https://code.google.com/p/mock/issues/detail?id=139). That makes
sense, as on _unpickling_ (which could be in an entirely new Python process),
how would `pickle` know what original class was being mocked?

