I was porting some old python 2 code and needed to create some bytes constants from int.
I hit this oddity is it a bug?
Python 3.11.0 (v3.11.0:deaf509e8f, Oct 24 2022, 14:43:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
:>>> 3.to_bytes(1, 'little')
File "<stdin>", line 1
3.to_bytes(1, 'little')
^
SyntaxError: invalid decimal literal
:>>> (3).to_bytes(1, 'little')
b'\x03'
It’s hard to parse that sort of thing, because 3. is a float literal. (Digits following the decimal are optional - I would personally always have at least one, but 3. is the same literal as 3.0 according to the parser.) So having a keyword after that is a tad tricky. Usually, the (3).to_bytes style is going to be fine, but if it really is a literal, just use a bytestring literal? The to_bytes method is more useful when you have some other way of getting the number (like OPCODE_SPAMINATE = 123 and then needing OPCODE_SPAMINATE.to_bytes() to get the byte version ofi t).