1. LPU MCA Semester 1
  2. CAB106
  3. Unit 5

CAB106 · Unit 5: Exception handling and file management

Serialization using the pickle module

10 practice questions

Key points

  • pickle serialises objects to bytes and rebuilds them
  • Use binary modes wb and rb
  • Pickle keeps types and shared references
  • Never unpickle untrusted data

Serialization converts an object into a byte stream that can be stored or sent; deserialization rebuilds it. Python's pickle module does this for almost any object, including user-defined class instances and nested containers.

FunctionPurpose
pickle.dumps(obj)Object to a bytes object
pickle.loads(data)Bytes back to an object
pickle.dump(obj, f)Write to a binary file
pickle.load(f)Read from a binary file

Files for pickling must be opened in binary mode (wb, rb); a text-mode file raises TypeError. The restored object is an equal but separate copy, tuples stay tuples (unlike JSON), and objects that were shared inside one dump stay shared. Functions are pickled by name, so a lambda cannot be pickled and raises PicklingError.

Pickle is Python-specific and not safe for untrusted data, because loading a crafted pickle can execute arbitrary code. For data exchange with other systems use JSON.

Exam trap: pickle output is bytes, so use wb and rb, not w and r.

Try two questions

Question 1 · Tier 3, Apply

Why is it dangerous to unpickle data from an untrusted source?

  1. A crafted pickle can run arbitrary code while it is being loaded
  2. The loaded data always exceeds the memory available to Python
  3. Unpickling silently changes every number to a string
  4. Unpickling permanently locks the file against later edits
Show the answer

A. Unpickling can call arbitrary functions, so only load pickles you trust.

Why not B: Size is not the security concern.

Why not C: Pickle preserves types such as numbers.

Why not D: Unpickling does not lock files.

Question 2 · Tier 2, Understand

Which mode string should be used to open a file for writing pickled data?

  1. w
  2. wt
  3. wb
  4. w+
Show the answer

C. Pickle produces bytes, so the file must be opened in binary mode.

Why not A: w is text mode, but pickle writes bytes.

Why not B: wt is explicit text mode, so it also expects str.

Why not D: w+ is text read-write mode, which still expects str.