[Python-ideas] Direct byte<->int conversions (was Re: bitwise operations on bytes)

Nick Coghlan ncoghlan at gmail.com
Mon Aug 10 15:53:53 CEST 2009


Antoine Pitrou wrote:
> Nick Coghlan <ncoghlan at ...> writes:
>> int.to_bytes(data, *, size=0, little_endian=None, signed=True)
> 
> It would be better IMO if this method belonged to the target type, so that you
> can write `bytearray.from_int()` without going through an intermediate bytes
> object.
> 
> What if `data` is equal to 0? Does it return an empty bytes object? It doesn't
> look dangerous to do so, so I'd say go for it.

Actually, that's just a typo after copying the from_bytes signature line
when writing my message. int.to_bytes would just be a normal instance
method. If the value was 0, then the result would be a single byte with
the value zero (or all zeroes if a size was specified).

As far as bytearray goes, my original post did suggest that approach
(i.e. class methods on the target types), but that then gets tedious as
every new type that wants to support conversion from an integer needs to
either go through one of the existing types or else have it's own C
extension call the underlying C API directly.

Something analagous to the file.readinto() method seems like a more
appropriate solution for populating the mutable types.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list