if bytes != str:

Jon Ribbens jon+usenet at unequivocal.eu
Sun Aug 4 14:21:22 EDT 2019


On 2019-08-04, Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
> I read and learn the the following code now:
>
> https://github.com/shadowsocksr-backup/shadowsocksr-libev/blob/master/src/
> ssrlink.py
>
> In this script, there are the following two customized functions:
>
> ----------
> def to_bytes(s):
> 	if bytes != str:
> 		if type(s) == str:
> 			return s.encode('utf-8')
> 	return s
>
> def to_str(s):
> 	if bytes != str:
> 		if type(s) == bytes:
> 			return s.decode('utf-8')
> 	return s
> ----------
>
> I've the following confusion on the above code:
>
> Why should use `if bytes != str:' here?  I mean, this will always return 
> True, IMO.  

It's a Python 2 v Python 3 test. I would suggest that the following
would be a better way of achieving the same end, but more efficiently,
given that a Python 2 interpreter isn't going to magically turn into
a Python 3 interpreter halfway through executing a program:

    if bytes is str:
        to_bytes = lambda s: s
        to_str = lambda b: b
    else:
        to_bytes = lambda s: s.encode('utf-8') if isinstance(s, str) else s
        to_str = lambda b: b.decode('utf-8') if isinstance(b, bytes) else b




More information about the Python-list mailing list