python3 byte decode

Terry Reedy tjreedy at udel.edu
Fri Nov 3 15:53:20 EDT 2017


On 11/3/2017 5:24 AM, Ali Rıza KELEŞ wrote:
> Hi,
> 
> Yesterday, while working with redis, i encountered a strange case.
> 
> I want to ask why is the following `True`
> 
> ```
> "s" is b"s".decode()
> ```
> 
> while the followings are `False`?
> 
> ```
> "so" is b"so".decode()
> "som" is b"som".decode()
> "some" is b"some".decode()
> ```
> 
> Or vice versa?
> 
> I read that `is` compares same objects, not values. So my question is
> why "s" and b"s".decode() are same objects, while the others aren't?

For the same reason as

 >>> a = 1
 >>> b = 1
 >>> a is b
True
 >>> a = 1000
 >>> b = 1000
 >>> a is b
False

For CPython, 'small' ints are cached on startup.  Ditto for 'small' 
strings, which I think includes all 128 ascii chars, and maybe latin1 
chars.  Details depends on the implemention and version.  The main use 
of 'is' for immutable builtins is for developers to test the 
implementation in the test suite.

-- 
Terry Jan Reedy





More information about the Python-list mailing list