[issue38060] precedence (relational, logical operator)not working with single value

Steven D'Aprano report at bugs.python.org
Mon Sep 9 05:53:49 EDT 2019


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Tim is correct, the behaviour is right, however the docs could be clearer.

I think what you are missing is that ``or`` and ``and`` are short-circuiting operators. So in the expression

    9 or (anything)

the "anything" expression never gets evaluated because 9 is a truthy value. You might get a better example of what is happening if you disassemble the byte-code:


py> from dis import dis
py> dis(compile("9 or 7 < 'str'", '', 'eval'))
  1           0 LOAD_CONST               0 (9)
              3 JUMP_IF_TRUE_OR_POP     15
              6 LOAD_CONST               1 (7)
              9 LOAD_CONST               2 ('str')
             12 COMPARE_OP               0 (<)
        >>   15 RETURN_VALUE


Another way to see the order of evaluation is if we make the left hand operand falsey:


py> print("first") or print("second") < 'str'
first
second
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < str()

In this case, the order of operations is:

- evaluate ``print("first")`` (returns None)
- since None is falsey, evaluate ``print("second") < 'str'``
- which prints the word "second", then raises an exception.


We can get rid of the exception:

py> print("first") or str(print("second")) < 'str'
first
second
True


I can see how the docs are a little bit confusing if you don't remember that ``or`` and ``and`` are short-circuiting operators. If you would like to propose an improvement to the docs, please suggest something. But the behaviour is correct and is not a bug.

https://docs.python.org/3/reference/expressions.html#operator-precedence

----------
nosy: +steven.daprano

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38060>
_______________________________________


More information about the Python-bugs-list mailing list