Really copy dict, not only the ref to the dict.

Code comment says dict is copied, but only ref to dict is copied:

  # Create a copy of the object that we will return.
  r = ret

Here, the local var 'r' is pointing to the exact same dict as the 'ret' argument.

I use <object>.copy() because 'ret' is expected to be a dict-like object, and
dict have a (shallow) copy method.
Shallow copy seems sufficient here because the '_generate_doc' method and
subsequent users of its return only modify 1st level keys.