A restricted unpickler lowers risk but does not make pickle safe for untrusted data. The Python docs show how to override find_class to allow only a few classes, and also warn that allow listing needs care. If the data is untrusted, use a format like JSON instead.
Myth and fact
Myth: "If I restrict which classes can load, pickle is safe."
Fact: It narrows the attack surface when done carefully, but the Python docs still open with a warning that the module is not secure and that you should only unpickle data you trust.
What the mechanism does
By default, the docs say, unpickling imports any class or function found in the pickle data. That lets a crafted stream call things like a shell command function. The documented fix is to subclass the unpickler and override find_class, which is called whenever a global is requested. Your override returns allowed items and raises an error for the rest.
The docs include an example that allows only a handful of harmless built in types, and shows a malicious stream being rejected with an unpickling error naming the forbidden global.
Why it still is not a guarantee
The docs warn that allow listing needs care, and use an example involving eval reachable through a permitted looking path to make the point. Every allowed callable is a chance to be misused, and data science libraries expose many callables. A list broad enough to load a real model or DataFrame can be broad enough to be abused.
It also guards only the loading step. It does not tell you the data inside is correct or unmodified.
What the docs suggest instead
| Need | Option from the docs |
|---|---|
| Untrusted input | JSON, which does not in itself create an arbitrary code execution vulnerability when deserialized |
| Tamper detection | Sign data with HMAC. This addresses tampering only, not untrusted sources |
| Looking inside a suspect file | Use pickletools, which does not execute bytecode |
For data pipelines
- Move cross team exchange to Parquet, CSV or JSON where the data is plain data. This is our recommendation rather than a quoted doc claim.
- Keep pickle for files only your own job can write and read.
- If you must load pickle from elsewhere, restrict globals with an allow list, test it against malicious samples, and run the load in a sandbox with no credentials.
- Sign and verify the file before loading, so tampering is caught first.
See also what to do instead of pickle and whether joblib model files are safe.
Quick check
Does HMAC signing fix untrusted pickle?
No. It detects tampering by someone without the key. It does not make a file from an untrusted source safe to load.
What is the safest way to look at a pickle file?
Use pickletools to read it without executing it, as the Python docs describe.
Safeguard scanning flags vulnerable Python libraries in your data projects, with a free scan at gold.safeguard.sh/scan.
Sources
Last reviewed: 19 October 2026.