The startElementNS method in the XMLGenerator ignores the encoding set. it does: self._out.write(' xmlns:%s="%s"' % (prefix, uri)) whereas it should have done: self._write(' xmlns:%s="%s"' % (prefix, uri)) Issue 938076 was similar to this, but for a different method.
I came across the bug when trying to write XML documents to StringIO objects. This does not work, since the output contains a mix of unicode and str objects, and StringIO gets confused. A better alternative is to use io.BytesIO, since all output should be encoded, but this also throws an error since it gets some unicode objects. The attached file breaks for both cases (comment/uncomment StringIO to test)