Login
You're viewing the ruby.social public feed.

Replies

  • Nov 1, 2026, 6:48 PM

    I have to admit that I would never have thought of option 3 and the place I saw it was code that was probably generated by an LLM. But it has its merits... the fallback is clearly an argument to a function.
    I love if-else assignments but they are rarely as short as in this example and then they become unreadable.
    Maybe there's an even better solution that I'm not aware of? Better as in pythonic or elegant. I'm not so much concerned about speed.

    💬 0🔄 0⭐ 0
  • Ryanyantor3d@mas.to
    Nov 1, 2026, 7:13 PM

    @compfu I usually do this

    ```python
    item = (items or [None])[0]
    ```

    or this

    ```python
    item, *_ = items or [None]
    ```

    As a bonus it also handles the situation where `items` is None in case you're working against an API that returns None instead of an empty list.

    Not that any API would ever do something so heinous. maya.

    💬 0🔄 0⭐ 1
  • 💬 0🔄 0⭐ 0
  • Ryanyantor3d@mas.to
    Nov 1, 2026, 7:43 PM

    @compfu You can do so much with it!

    first, *__ = items
    first, *__, last = items
    *__, last = items
    __, *middle, __ = items

    💬 0🔄 0⭐ 1
  • 💬 0🔄 0⭐ 0
  • Nov 1, 2026, 7:53 PM

    @compfu I see try/except is not getting much love in the poll, and to be fair I agree it's usually not the *best* option, but I do think it's a reasonable choice. Python is built to support exception handling pretty well, and I think a lot of people are too reluctant to use try/except even in cases where it would be one of the best options. (Possibly due to communal wisdom carried over from C++ and Java and so on, where throwing exceptions is relatively inefficient.)

    #Python

    💬 1🔄 0⭐ 0
  • Nov 1, 2026, 8:25 PM

    @diazona Yes, it has its merits. It's good for logging or alerting the user. You get those if/else branches for free ("using {item}" vs. "no item found").

    In another reply, somebody suggested that the try/except block also makes it clear that using the fallback case is exceptional, not the norm.

    💬 0🔄 0⭐ 0
  • Nov 1, 2026, 7:56 PM

    @compfu

    Before the ternary "operator" was available in Python expressions, I used to see this a fair bit:

    item = (things or [None])[0]

    I probably wouldn't use it today, though.

    💬 1🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0