How to write code that works in both Python 2 and Python 3?

前端 未结 6 443
死守一世寂寞
死守一世寂寞 2021-01-03 02:28

A Django website I maintain currently uses Python 2.7 but I know that I\'ll have to upgrade it to Python 3 in a couple of months. If I\'m writing code right now that has to

6条回答
  •  抹茶落季
    2021-01-03 02:48

    In addition to importing from future, there is also the six project that aims to provide api compatibility between Python 2 and Python 3: https://pypi.org/project/six/.

    Your example code could be made compatible between version 2 and 3:

    import six
    
    for key, value in six.iteritems(dict):
        log.info("{0}: {1}".format(key, value))
    

    There are still things that won't be compatible between 2 and 3 like f-strings.

提交回复
热议问题