[Python-ideas] PEP 505: None-aware operators

Paul Moore p.f.moore at gmail.com
Tue Jul 24 03:44:50 EDT 2018


On 24 July 2018 at 08:38, Grégory Lielens <gregory.lielens at gmail.com> wrote:
>
>
> On Tuesday, July 24, 2018 at 9:28:02 AM UTC+2, Brice Parent wrote:
>>
>> Le 24/07/2018 à 00:39, Chris Angelico a écrit :
>> > On Tue, Jul 24, 2018 at 8:22 AM, Thomas Jollans <tj... at tjol.eu> wrote:
>> ...
>> > What about:
>> >
>> > 5 < x < 10
>> >
>> > Can you add parentheses to that to "make precedence and evaluation order
>> > clear"?
>> Correct me if I'm wrong, but to my knowledge, this is just a shorthand
>> to `5 < x and x < 10`.
>
>
> I learned something here:
>>>>   -5<-2<-1<=-1>-3
> True
>
> I wonder how this works, especially as < and friends have magical __
> methods... How is it expanded in tne AST?

>>> import ast
>>> m = ast.parse('-5<-2<-1<=-1>-3')
>>> ast.dump(m)
'Module(body=[Expr(value=Compare(left=UnaryOp(op=USub(),
operand=Num(n=5)), ops=[Lt(), Lt(), LtE(), Gt()],
comparators=[UnaryOp(op=USub(), operand=Num(n=2)), UnaryOp(op=USub(),
operand=Num(n=1)), UnaryOp(op=USub(), operand=Num(n=1)),
UnaryOp(op=USub(), operand=Num(n=3))]))])'

Looks like there's a Compare node that takes a list of operators - and
indeed the docs say (at
https://docs.python.org/3.7/library/ast.html#abstract-grammar)

    Compare(expr left, cmpop* ops, expr* comparators)

Paul


More information about the Python-ideas mailing list