python - Best way to automatically decode bytes -


currently using following (works in both py2 , 3)

if isinstance(string, bytes):     string = string.decode('utf-8') 

however, there better way both python 2 , 3 compatible. seems missed obvious. in python 2 simple str(string)

edit:

context: making library/util class accepts redis client object. object has option automatically decode responses (default off), or return plain bytes. given response object, can either bytes or str depending on how object configured

the best way avoid problem in first place. use "unicode sandwich" technique - convert data strings after read it, , convert bytes when need serialize it. if this, shouldn't end object might strings or might bytes, shouldn't ever need detect whether has been decoded yet or not.


if really can't reason (if third-party code hand either based on conditions don't control), next easiest thing use library six, makes easier write code works in both python 2 , python 3. among other things, has variable called six.binary_type, bytes in python 3 , str in python 2 making possible modify existing technique to:

if isinstance(string, six.binary_type):     string = string.decode('utf-8') 

note that, in python 2, str(string) not give same type of object - gives str, fills same role python 3's bytes. want unicode(string, 'utf-8'), might use decode since has same name in both.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -