Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python - Pickle.dump to variable

I'm new in python and i wanted to know if there is a solution for this problem:

I know that this may sound strange but i want to save the pickle.dump data into a variable. I begin to think that may i could bypass it by making a fake class to instead of writing in a file, writing in a variable:

class PickleDatatoVar(object):
def __init__(self):
    self.data = None
def write(self, data):
    self.data = data
def get(self):
    return self.data

and then:

pick = PickleDatatoVar()
pickle.dump(Int, pick)
var = pick.get()

Nothing is presented as error, but the output is just a '.'

So is there a solution to instead of saving that in a file saving into a variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for an in-memory file object; in Python 2 that's cStringIO.StringIO(), for Python 3 io.BytesIO(); these act just like file objects and you can have pickle.dump() write to these.

However, the easier path would be to use pickle.dumps() to dump straight to a string object instead.

Under the hood, what pickle.dumps() does for you is create an in-memory file object, write the pickle data to it and retrieve the string result for you; see the source code:

def _dumps(obj, protocol=None, *, fix_imports=True):
    f = io.BytesIO()
    _Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
    res = f.getvalue()
    assert isinstance(res, bytes_types)
    return res

but this way you don't have to do that extra work yourself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...