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

前端 未结 6 565
死守一世寂寞
死守一世寂寞 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:44

    six and future is a golden rule, enough to make easy a coming migration

    add to every python2 file, this as first line:

    from __future__ import absolute_import, unicode_literals
    

    use below working with strings, iteration, metaclasses, ...

    isinstance(sth, six.string_types)
    
    six.iteritems(dict)
    
    @six.add_metaclass(Meta)
    

    and so on six reference

提交回复
热议问题