python兼容性问题

  1. 获取python版本
PY_VERSION = sys.version_info[:3]
PY2 = PY_VERSION[0] == 2
PY3 = not PY2
  1. 定义python不同版本的处理
if PY2:
    # io.StringIO only accepts u'foo' with Python 2.
    from StringIO import StringIO


    def py2to3(cls):
        if hasattr(cls, '__unicode__'):
            cls.__str__ = lambda self: unicode(self).encode('UTF-8')
        return cls

else:
    from io import StringIO


    def py2to3(cls):
        if hasattr(cls, '__unicode__'):
            cls.__str__ = lambda self: self.__unicode__()
        if hasattr(cls, '__nonzero__'):
            cls.__bool__ = lambda self: self.__nonzero__()
        return cls

  1. 使用
@py2to3
class ConnectionCache(object):
  xxx

原文地址:https://www.cnblogs.com/amize/p/14892670.html