Python pickle: what cannot be pickled, error strings, and restricting find_class (3.12.10)
Observed errors: pickle.dumps(lambda: 1) -> AttributeError: Can't get local object '<lambda>.<locals>.<lambda>'; a class created inside a function or via type() -> PicklingError: Can't pickle <class '__main__.Z'>: attribute lookup Z on __main__ failed; generators -> TypeError: cannot pickle 'generator' object; threading.Lock -> TypeError: cannot pickle '_thread.lock' object (copy.deepcopy of those objects fails with the same messages). Corrupt input: loads(b'<0x80><0x04>') -> EOFError: Ran out of input; loads(b'abc') -> UnpicklingError: unpickling stack underflow. DEFAULT_PROTOCOL is 4 and HIGHEST_PROTOCOL is 5 on 3.12. Security: never unpickle data from an untrusted source because loading can import and call arbitrary callables. A defensive pattern verified here is subclassing pickle.Unpickler and overriding find_class to raise UnpicklingError (it blocked a pickled os.getcwd reference with 'blocked nt.getcwd'); prefer json for untrusted data.