Why is “1.real” a syntax error but “1 .real” valid in Python?

I guess that the . is greedily parsed as part of a number, if possible, making it the float 1., instead of being part of the method call.

Spaces are not allowed around the decimal point, but you can have spaces before and after the . in a method call. If the number is followed by a space, the parse of the number is terminated, so it’s unambiguous.

Let’s look at the different cases and how they are parsed:

>>> 1.real    # parsed as (1.)real  -> missing '.'
>>> 1 .real   # parsed as (1).real  -> okay
>>> 1. real   # parsed as (1.)real  -> missing '.'
>>> 1 . real  # parsed as (1).real  -> okay
>>> 1..real   # parsed as (1.).real -> okay
>>> 1 ..real  # parsed as (1)..real -> one '.' too much
>>> 1.. real  # parsed as (1.).real -> okay
>>> 1 .. real # parsed as (1)..real -> one '.' too much

Leave a Comment