How math operators are identified

How does simple 2 ++ 2 work behind the scenes in Python?

If we type this in the Python interpreter :

>>> 2+++--2
4
>>> 2+++*2
  File "<stdin>", line 1
    2++*2
       ^
SyntaxError: invalid syntax

Looking for syntax errors I noticed that Python was designed and implemented by Python designers.

Python is said to be open source, so I started learning more about it. I read a lot of articles about Python implementation using cpython .

So, here the Python compiler easily identifies these statements ++*%-. Because it is written using the C language . And C uses some direct assembly code compiler, which is then converted to machine code.

Question 1: . How is the Python compiler designed to identify statements? (regarding lexical and syntactic functionality)

Question 2 . How to change this simple behavior of the Python interpreter, where it can cause a syntax error for using multiple operators in the same way as for multiplication

>>> 2**2
4
>>> 2***2
  File "<stdin>", line 1
    2***2
       ^
SyntaxError: invalid syntax

I read these cpython files: compile.c parser.c , readline.c

But I did not come across such files in the exception handling mechanism for a syntax error.

Update:

I'm still looking and waiting for an answer to question-2

+4
source share
1 answer

. -2 " ". --2 - " ( )" " ". 2+++--2 " ", 2+2 4. +2 -2 , *2 , .

, , .

, . (...) , - . Python Bachus Naur. https://docs.python.org/2/reference/expressions.html#unary-arithmetic-and-bitwise-operations :

u_expr ::=  power | "-" u_expr | "+" u_expr | "~" u_expr

m_expr ::=  u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr
            | m_expr "%" u_expr

a_expr ::=  m_expr | a_expr "+" m_expr | a_expr "-" m_expr

, Python. , , :

u_expr ::=  "2" | "-" u_expr | "+" u_expr

m_expr ::=  u_expr | m_expr "*" u_expr

a_expr ::=  m_expr | a_expr "+" m_expr | a_expr "-" m_expr

, a u_expr 2, + -, u_expr, a u_expr: '2', '-2', '+2', '+-2', '++++---++2'.

An m_expr u_expr, a m_expr, a *, u_expr. 2, 2*2, 2*+2, 2*++-+2 .

An a_expr m_expr, a a_expr, , m_expr. 2, 2*2, 2+2, 2+2*2, 2++2*-2 ..

, 2+++*2. a_expr. 2+, - a_expr "+" m_expr. 2 a_expr, +, , - ++*2 m_expr. , a_expr "2", .

2+++--2, , a_expr. , 2 a_expr, +, ++--2, m_expr.

2***2 , , Python , , Python. , , , , ** :

power ::=  primary ["**" u_expr]

, Haskell, , - 2+2, . ***, Python PEP Python.

, , - , . , , " ", " ", "- " " "

+7

Source: https://habr.com/ru/post/1668592/


All Articles