DAF
DAF

Reputation: 145

Pickle (no file IO): TypeError: a bytes-like object is required, not 'str'

I am getting this TypeError from object serialization alone, ie. no file IO involved (unlike other similar posts). One piece of the code is:

for itr in range(numiters):
    #Sample from proposal distribution
    d_star,Jratio,R_star,step = proposal(d_t,R_t,X,Y,alpha)
    #Compute the new posterior value, if necessary
    a_star = Pickle.dumps(d_star[:R_star+1])
    print(type(a_star))
    permsdic[a_star] = ...

and another is:

for perm in permsdic.keys():
    print(type(perm))
    print(perm)
    d_t = Pickle.loads(perm)

and yet I get the above error in: d_t = Pickle.loads(perm) The output of print statements in the first block is:

class 'bytes'

and yet in 2nd block it is somehow:

class 'str'

b'\x80\x03]q\x00(K\x01K\x03K\x05K\x0cK\x00e.'

This is in Python 3.6 (I am trying to adapt an older Python library)

Upvotes: 1

Views: 756

Answers (1)

DAF
DAF

Reputation: 145

I was able to make it work by using eval() function, i.e. the following works

for perm in permsdic.keys():
    print(type(perm))
    print(perm)
    d_t = Pickle.loads(eval(perm))

I still don't understand why this is necessary...

Upvotes: 2

Related Questions