Skip to content
Categories:

Python Conference NL 2023

Post date:
Author:

Today I attended the Python Conference NL in the Jaarbeurs in Utrecht, The Netherlands. It was super-well organised by Ordina. Thanks!!

One of my colleagues was not able to make it to the conference. My colleague sent him this picture in our developer chat:

Eagle-eyed as he was, he commented: oh I did not know you could do that, have two ifs on a single line!

The code in question was this:

    if a >= n if mode_is_list_to else i >= n:
        break

https://github.com/jhbuhrman/refactor-into-generators/blob/0b40c848e494d2a7af5f5e7ba9938807d8a90175/src/fibonacci/first_two_combined.py#L6-L19

At first sight I suggested: oh but it kind of makes sense, if..if would probably be something like if..or no? My colleague who snapped the picture, wrote:

>>> if True if True else False:
...   print("test")
...
test
>>> r = a if True if True else False:
  File "<stdin>", line 1
    r = a if True if True else False:
        ^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression

We figured, that’s strange, the if in the first line is allowed but in the assignment it’s not. I thought: would that be a grammar issue?

After the talk we approached the speaker, the super friendly Jan-Hein Bührman, and asked him about the code construct he used. The point of this example code is that it’s not great code, and he refactors it later on. He also had to give it a small think. He quickly pointed out that in our example, in the first case, the ‘double if’ is allowed because it’s a ternary statement. In the second example, the case with the assignment, it’s just an invalid construct, it would read something like ‘a if True True’, and therefore it generates the syntax error.

Looking again at the code:

and now it makes sense. This is just a ternary: it checks mode_is_lists_to. If that is true, the ‘outer’ code reads if a >= n and otherwise the outer code reads if i >= n. The ternary generates a condition. It reads a bit funny but after just thinkin about what we’re looking at, it’s clear.

I was wrong two times, but had a good conference!