Much Ado About None: Sentinel Values in Python

(florianwilhelm.info)

22 points | by sebg 1 day ago

4 comments

  • lpghatguy 54 minutes ago
    When I was writing a bunch of Lua, I was a big fan of having a None sentinel value (Lua uses 'nil' for representing absence) and it was useful for a lot of things similar to Pydantic's MISSING.

    This distinction is something that I think is actually handy about JavaScript, and distinguishing between 'null' and 'undefined' is sometimes useful for similar reasons.

  • RantyDave 1 hour ago
    "A simple cache returns None both for a missing key and for a key that maps to None."

    No, it returns KeyError. Or at least it should.

    • 0cf8612b2e1e 6 minutes ago
      The author’s example chose to use the syntax that returns None on missing. If they wanted clarity the standard API does raise.

        cache = {“key”: “value”, “some input”: None}
        cache.get(“missing_key”}
      
      Vs

        cache[“missing_key”]
      
      There are better examples that could have been highlighted.
    • travisd 43 minutes ago
      it’s maybe less “pythonic” but at $dayjob we’ve very actively moved away from exceptions for things in favor of things that are statically type checked. too many things that become runtime bugs instead of type checking bugs.

      with match now being available, we even return explicit error objects and the ergonomics are pretty good (reminds me of rust).

    • lyorig 59 minutes ago
      Perhaps the author has had their fair share of run-ins with libraries that didn't think their API through like that. But yes, they should.
  • pwdisswordfishq 23 minutes ago
    So much trouble to avoid introducing the optional monad.
    • Waterluvian 17 minutes ago
      I’m curious what that would practically look like in Python.

      I bet this would be a good use of vibe coding. Experiment with what-ifs. I can imagine being able to “show not tell” and reduce the signal-to-noise of comment opinions.

    • woodruffw 19 minutes ago
      Python’s type system has union types (including Option), and using them is pretty ergonomic. As TFA points out the problem is that `None` gets contextually reused in all kinds of places where a proper sentinel type is more appropriate.
      • aw1621107 2 minutes ago
        Pretty sure Python's union types don't nest, though. If you could nest optionals then I feel that reduces the need for separate sentinel types since e.g., you can distinguish between "value not present" (None) and "null value present" (Some(None))
  • chowells 1 hour ago
    I like it. I can't see how to do better while remaining compatible with Python idioms.