Python 2/3 compatibility code that reads like English!

Chris Angelico rosuav at gmail.com
Wed Dec 10 11:43:36 EST 2014


So you have a string of text, either a Unicode string in Python 3, or
a byte string that's meant to be UTF-8. Most of the way through,
you're working with the native string type, for compatibility with
other sections of code. But then you want to be certain you're working
with a Unicode string...

if str is bytes:
    some_string = some_string.decode('UTF-8')

I just love how that condition reads. Who says cross-branch
compatibility code has to be ugly? :)

ChrisA



More information about the Python-list mailing list