This is interesting and seems very useful, but it doesn't seem like it belongs in the pg module.  It seems like it might be better to submit this as a pull request against stdlib.  @jeffmccune any thoughts?