Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

So I saw these two questions on twitter. How is 1.real a syntax error but 1 .real is not?

>>> 1.real   File "<stdin>", line 1     1.real          ^ SyntaxError: invalid syntax >>> 1 .real 1 >>> 1. real   File "<stdin>", line 1     1. real           ^ SyntaxError: invalid syntax >>> 1 . real 1 >>> 1..real 1.0 >>> 1 ..real   File "<stdin>", line 1     1 ..real        ^ SyntaxError: invalid syntax >>> 1.. real 1.0 >>> 1 .. real   File "<stdin>", line 1     1 .. real        ^ SyntaxError: invalid syntax 
like image 396
AlexLordThorsen Avatar asked Jun 24 '15 21:06

AlexLordThorsen


People also ask

Why does Python always say invalid syntax?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.


1 Answers

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 
like image 82
tobias_k Avatar answered Sep 19 '22 17:09

tobias_k