fix for http://bugs.python.org/issue17980 in code backported from the python3 stdlib

Signed-off-by: Marcus Smith <qwcode@gmail.com>