Pickling with Blender

I am trying my hand at pickling with Blender, but I am running into trouble right from the start. I have the following sample code to test the concept:

# Filename: pickling.py

import cPickle as p

class TestClass:

filename = 'file.data'

var = TestClass()
#var = 1

print var
f = file( filename, 'w' )
p.dump( var, f )

del var

f = file( filename )
storedvar = p.load( f )
print storedvar
# pickling.py
<__main__.TestClass instance at 0x2af2f15d7560>
<__main__.TestClass instance at 0x2af2f15d7560>

Looks good to me. So now when I try to run that script with Blender, I get the following:

# /usr/bin/blender -P bin/pickling.py
Compiled with Python version 2.4.
Checking for installed Python... got it!
<__main__.TestClass instance at 0x2aaaaac0b290>
Traceback (most recent call last):
  File "pickling.py", line 21, in ?
AttributeError: 'module' object has no attribute 'TestClass'

Error executing Python script from command-line:
bin/pickling.py (at line 21).

Blender quit

If I change to ‘var = 1’, then the code works just fine. What is it about classes that I am missing?

I googled pickling and python and get that it has to do with object serialization and/or persistence? What are you trying to do actually? Thanks,



I am using a script to take data from an input file and load it into a list containing instances of a class that I have defined. Then I want to take that list and pickle it so I can use that data in another script without having to reparse from the ascii file.

Simplified summary: I have data in one script that needs to be used in another.

To get around needing pickle, I was using the Registry module included in the Blender API. However, I feel that is a bad idea because that will load all the data from the input file into memory and I cannot predict how large the file will be, nor can I predict how much RAM the user will have.

I have just tested both your script and one of my own and get the same result. I don’t know if there is some version compatibility issue with Blender or what, but I have many times in the past used the python pickler from Blender to export models to my game engine.

By changing the cPickle module to plain old python pickle, you get a traceback showing that for some reason it cannot find the class definition. I’m not sure how this can be fixed.

Thats very puzzling, I see the same problem here when I run it from Blender, its saves the pickle file OK, but has problem reading it back to the variable. I dont think there is anything wrong with your script, as it works OK if I run it from a non Blender shell
Maybe its a Blender specific python bug ?

I’m glad to see that I am not the only one getting this result. I’ll take another look through the bug tracker, but last time I looked I didn’t come across anything.