3.int_bytes(1, 'little') SyntaxError - is this a bug?

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).

1 Like

It is also possible to put a space between the object and the dot operator, so you could also write

3 .to_bytes(1, 'little')

(though probably less weird to just use parens)

2 Likes

Thanks, I hate it :joy:

No, it’s not a bug. 3. looks like a float, so the interpreter is expecting a decimal digit after the dot and finds the letter t instead.

Just put brackets around the 3: (3).to_bytes(1, 'little').

BTW, that code doesn’t work in Python 2 either, you get a SyntaxError with a less informative message:

>>> 3.to_bytes(1, 'little')
  File "<stdin>", line 1
    3.to_bytes(1, 'little')
             ^
SyntaxError: invalid syntax

If you hate that, wait til you see this!

>>> ("  My hovercraft is full of eels  " . strip  ( ) 
...                                      . upper  ( )
...                                      . split  ( )
...                                      [ 1 : : 4 ]
...                                      )
['HOVERCRAFT', 'EELS']
2 Likes

Oh its a float! I see that now you point that out.

Thanks Chris.

I code using () to make multiline statements all the time, love that construct, especialy to avoid \ at end of line.

I see not case of confusion in that code. The spaces and new lines make no difference to the parsing and its not ambigious. Or did I miss something?

I think the point was that it is very unusual to see spaces around those operators: . () [] [::] which makes the code difficult to read.

Personally I find the lack of space that makes code hard to read not extra spaces.