Back
+20 XP
Concept

Python Object Serialization with pickle (Security Warning)

`pickle` serializes arbitrary Python objects into binary bytes. CRITICAL WARNING: Never unpickle untrusted data! Arbitrary bytecode injection in `pickle.loads()` can execute malicious shell commands 🛑.

python
import pickle

data = {"model_name": "ResNet", "weights": [0.25, 0.75, 0.12]}

# Serialize to bytes:
serialized = pickle.dumps(data)
print(f"Serialized bytes length: {len(serialized)} 📦")

# Deserialize:
restored = pickle.loads(serialized)
print(f"Restored model: {restored['model_name']} ✅")

# 24. Python Object Serialization with pickle (Security Warning) `pickle` serializes arbitrary Python objects into binary bytes. CRITICAL WARNING: Never unpickle untrusted data! Arbitrary bytecode injection in `pickle.loads()` can execute malicious shell commands 🛑. ```python import pickle data = {"model_name": "ResNet", "weights": [0.25, 0.75, 0.12]} # Serialize to bytes: serialized = pickle.dumps(data) print(f"Serialized bytes length: {len(serialized)} 📦") # Deserialize: restored = pickle.loads(serialized) print(f"Restored model: {restored['model_name']} ✅") ``` For public APIs and untrusted user input, always use JSON, Protocol Buffers, or MsgPack. Reserve `pickle` strictly for trusted internal process caching! 🛑 --- ### Question Why is `pickle.loads()` strictly prohibited on untrusted data from network clients? 🧠 - [ ] a. The pickle protocol allows arbitrary code execution during deserialization via `__reduce__` exploits 🛑 - [ ] b. Pickle is limited to ASCII strings only - [ ] c. It leaks your AWS root credentials - [ ] d. It causes a kernel panic in Linux --- ### Challenge Import `pickle`. Serialize list `['alpha', 'beta', 42]` with `pickle.dumps()`. Deserialize with `pickle.loads()` and print the restored list. 🎯 <details> <summary>Solution</summary> ```python import pickle original = ["alpha", "beta", 42] encoded = pickle.dumps(original) decoded = pickle.loads(encoded) print(decoded) ``` </details>

Checkpoint

Why is `pickle.loads()` strictly prohibited on untrusted data from network clients? 🧠

Practice

Import `pickle`. Serialize list `['alpha', 'beta', 42]` with `pickle.dumps()`. Deserialize with `pickle.loads()` and print the restored list. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks