[Python] Is there a tool like cparen (shows operator precedence) for python?

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    While I know the basics of python fairly well by now, every once in a while I write a more-complex expression and I'm not certain that I'm interpreting the operator precedence correctly. I can always put in extra parentheses, and there are some times when I don't mind doing so if I think it clarifies the expression; but often I think it looks clean as it is, and I think that I have the operator precedence right, but I just want to make sure.

    For the C programming language, there was a great tool called "cparen" which yielded a fully-parenthesized version of an expression, thus indicating the operator precedence. Usually used interactively when exactly the above kind of question came up. For example, if cparen's input is

    a&b + c<<3 * 4


    then its output would be

    a&((b+c)<<(3*4))


    which may be surprising to people who don't know the bizarre history of '&' (and '|'), or the way C thinks of bitwise operators (e.g. '<<'). (And, obviously, would be educational to anyone who wrote the expression with spacing like that, and thus obviously misunderstands the precedence.)

    Python's operator-precedence table isn't as wacky nor as history-laden as C's, but I'd still find such a tool extremely useful for this situation... is there anything like this, or with a similar use to this?

    Continue reading...

Compartilhe esta Página