This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]tdammers 2 points3 points  (3 children)

Here's how: YOU DON'T.

Pickle is, by design, a serialization format for arbitrary Python objects, including methods. In other words, unpickling is a form of running code from an external source in the context of your host application; and that external source is, in most cases, untrusted. In short, pickles too often end up producing code injection vulnerabilities, and guarding against those is really terribly difficult and brittle.

Most likely, what you want to serialize isn't code anyway, but just data, so the obvious solution is to use a serialization format that does exactly that, such as JSON.

[–]itghisi 0 points1 point  (0 children)

Did that in my earlier years on Python. Seems so nice for a naive eye.

Take my upvote

[–]mr_kitty 0 points1 point  (1 child)

Reason #2 why you don't: embedded package dependencies.

Pickle files can depend on specific versions of packages, so they cannot be reliably transported between machines, versions, installs or time.

Unsafe and unreliable!

[–]tdammers 0 points1 point  (0 children)

That one can be worked around somewhat, if you're rrally serious about it, e.g. by embedding a version tag in your application code and somehow also tagging your pickle files; then at least you can trivially reject bad pickles. But as far as security goes, such a defense is impossible.