News for hackers. Stuff that matters.
Re:What the Fuck Python by jnpnj on Saturday July 19, 2025 @04:44PM (#44619204)
Oh yeah, that's a great one, there must be a compounded boolean expression logic escaping us

I'll add:

    >>> False == False in [True]
    False
    >>> True == True in [True]
    True
ps: some ast poking

    >>> ast.show(ast.parse("False == False in [False]"))
    Module(
      body=[
 Expr(
   value=Compare(
     left=Constant(value=False),
     ops=[
       Eq(),
       In()],
     comparators=[
       Constant(value=False),
       List(
  elts=[
    Constant(value=False)],
  ctx=Load())]))])

    >>> ast.show(ast.parse("(False == False) in [False]"))
    Module(
      body=[
 Expr(
   value=Compare(
     left=Compare(
       left=Constant(value=False),
       ops=[
  Eq()],
       comparators=[
  Constant(value=False)]),
     ops=[
       In()],
     comparators=[
       List(
  elts=[
    Constant(value=False)],
  ctx=Load())]))])
note the first tree as one Comparator node with multiple ops, time to read the spec to know how these are evaluated
Re:What the Fuck Python by Jtsummers on Saturday July 19, 2025 @05:05PM (#44619401)
The document explains it. When dealing with these comparators, when chained they get separated and you have the equivalent of this:

  False == False in [True]
  =>
  (False == False) and (False in [True])
If you put it into a function like this:

  def foo(): return False == False in [True]
And then disassemble it you'll get this byte code (3.13, may vary by version):

  RESUME                   0
     LOAD_CONST               1 (False)
     LOAD_CONST               1 (False)
     SWAP                     2
     COPY                     2
     COMPARE_OP              72 (==)
     COPY                     1
     TO_BOOL
     POP_JUMP_IF_FALSE        5 (to L1)
     POP_TOP
     LOAD_CONST               2 ((True,))
     CONTAINS_OP              0
     RETURN_VALUE
  L1:     SWAP                     2
     POP_TOP
     RETURN_VALUE
There is no literal `and` operation occurring here, instead it first does the `False == False`, then jumps if false or continues to the second comparison.

For the literals we've given it, it'll go on to the second comparison which will result in false since `False` is not in `(True,)`.

EDIT: And here's the non-chained version disassembled:

  def bar(): return (False == False) in [True]

     RESUME                   0
     LOAD_CONST               1 (False)
     LOAD_CONST               1 (False)
     COMPARE_OP              72 (==)
     LOAD_CONST               2 ((False,))
     CONTAINS_OP              0
     RETURN_VALUE
Re:What the Fuck Python by jnpnj on Thursday July 24, 2025 @03:10AM (#44667842)
Thanks a lot, brilliant