cPickle fails on manually compiled and executed Python function

Jan Gosmann jan at hyper-world.de
Mon Jul 17 21:37:23 EDT 2017


Hi,

today I came across some weird behaviour (a bug?) in Python 2.7.13 (on 
Linux) with the cPickle module. The pickle module works and so does the 
pickle module in Python 3.

I have a file fn.py with a minimal function definition:

```
def fn():
     pass
```

The actual code that I run is in a separate file (test.py):

```
import cPickle
import pickle

def load_pyfile(filename):
     source = ''
     with open(filename, 'r') as f:
         source += f.read()
     code = compile(source, filename, 'exec')
     loaded = {'__file__': filename}
     exec(code, loaded)
     return loaded

fn = load_pyfile('fn.py')['fn']

print(pickle.dumps(fn))
print('----')
print(cPickle.dumps(fn))
```

The first print works fine, but the one with cPickle leads to an 
exception. Here is the output:

```
c__main__
fn
p0
.
----
Traceback (most recent call last):
   File "test.py", line 17, in <module>
     print(cPickle.dumps(fn))
TypeError: expected string or Unicode object, NoneType found
```

I don't understand why the cPickle module behaves differently in this 
case. Is this expected? And if so, how do I fix it? Or can this be 
considered a bug? (In that case I could open an issue in the bug 
tracker.)

Cheers, Jan


More information about the Python-list mailing list