all Python 3picklefunction
pickle.loads()
deserialization
Restores an object from pickle bytes. Never call it on data from an untrusted source: such data runs code while loading.
Syntax
obj = pickle.loads(data, /, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None)
An object in a pickle can name any function with arguments through __reduce__, and loads will call it — the example below prints a line, a real attack runs a system command. Checking "after loading" is useless: the code has already run, and try/except does not help either. For data from the network, a cookie or a user use json.loads; if pickle is unavoidable, sign the bytes with hmac and verify the signature before loading.
Examples
import pickle
class Trap:
def __reduce__(self):
return (print, ('код выполнен при загрузке!',))
obj = pickle.loads(pickle.dumps(Trap()))
print(obj) # → None — loads вернул результат print(), а не Trap
import pickle
print(pickle.loads(pickle.dumps({'a': (1, 2)}))) # → {'a': (1, 2)}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy