Python 3.5, bytes, and %-interpolation (aka PEP 461)

Ethan Furman ethan at stoneleaf.us
Mon Feb 24 19:10:53 EST 2014


On 02/24/2014 03:55 PM, Steven D'Aprano wrote:
> On Mon, 24 Feb 2014 11:54:54 -0800, Ethan Furman wrote:
>
>> Greetings!
>>
>> A PEP is under discussion to add %-interpolation back to the bytes type
>> in Python 3.5.
>>
>> Assuming the PEP is accepted, what *will* be added back is:
>>
>> Numerics:
>>
>>     b'%d' % 10  --> b'10'
>>     b'%02x' % 10  --> b'0a'
>>
>> Single byte:
>>
>>     b'%c' % 80  --> b'P'
>
> Will %c also accept a length-1 bytes object?
>
> b'%c' % b'x'
> => b'x'

Yes.


>> and generic:
>>
>>     b'%s' % some_binary_blob --> b'tHE*&92h4' (or whatever)
>
> Will b'%s' take any arbitrary object, as in:
>
> b'Key: %s' % [1, 2, 3, 4]
> => b'Key: [1, 2, 3, 4]'

No.

> or only something which is already bytes (i.e. a bytes or bytearray
> object)?

It must already be bytes, or have __bytes__ method (that returns bytes, obviously ;) .


>> What is under debate is whether we should also add %a:
>>
>>     b'%a' % some_obj  --> b'some_obj_repr'
>>
>> What %a would do:
>>
>>     get the repr of some_obj
>>
>>     convert it to ascii using backslashreplace (to handle any code points
>>     over 127)
>>
>>     encode to bytes using 'ascii'
>>
>> Can anybody think of a use-case for this particular feature?
>
> Not me.

I find that humorous, as %a would work with your list example above.  :)

--
~Ethan~



More information about the Python-list mailing list