Live data from Hacker News

What's New in Python 3.12

docs.python.org

91–100 of 120 posts

Re: What's New in Python 3.12

#91
“The new syntax allows declaring TypeVarTuple and ParamSpec parameters, as well as TypeVar parameters with bounds or constraints:”

    ```
    ...
    type IntOrStrSequence[T: (int, str)] = Sequence[T]  # TypeVar with constraints
    ```

Why can’t the syntax be

    ```
    type IntOrStrSequence[T: int | str] = Sequence[T]
    ```

Re: What's New in Python 3.12

#92

So many breaking changes promulgated with covert version numbers—an unfortunate truth for Python and why the writing on the wall is clear—Python is not dependable—Go is the safer choice for business applications and services.

[deleted]

Re: What's New in Python 3.12

#93

I suspect people will use these comments to share their wishlist of Python features, so let me add that I really wish Python had a safe navigation operator, for when you are dealing with nested objects that could be None. I have been trying to parse a lot of XML and JSON in Python lately and a feature like that could really help reduce boilerplate checks. https://en.wikipedia.org/wiki/Safe_navigation_operator

I created a "NoDict" class that does this awhile back: https://github.com/BlackEarth/bl/blob/main/bl/no.py

Re: What's New in Python 3.12

#94

Earlier quoted context omitted.

I think that this is a hard problem and you're right that spamming KeyError everywhere is against the exceptionality of exceptions. But the current completely unchecked model is also misleading. I don't have such a great solution in mind but I think mypy should be able to verify each exception type is handled at some point in the stack. I know that it sounds vague, but these are my current unorganized thoughts.

Exceptions are always handled: Python exits while telling you about the exceptional situation. If you’re saying that I must handle an exception in my code rather than crash because my “fail early, fail often” design choices offend your religious preferences… then keep it to yourself and out of PEPs.

No I'm not saying that at all, I'm just saying that if you need a function to handle all exceptions, the type system should be powerful enough to express that. E.g. in a webserver if you have a handler that needs a wrapper like:

    def wrapper():
        try:
            return handler()
        except Exception:
            logger.exception("unknown exception")
            webserver.status = 500
the type system needs to be able to determine that "f doesn't raise an exception". For example, one way to do this can be that all functions by default raise exception and we type:

    def handler() -> T: ...

    def wrapper() -> NeverRaises[T]: ...
then we have

    webserver_add('GET', '/handler', wrapper)
so that

    def webserver_add(method: str, path: str, handle_func: Callable[[], NeverRaises[T]]) -> None: ...
which is type safer.

Of course, here we need to specially handle `KeyboardInterrupt`, signals and exceptions returned by `logger` etc. I would personally recommend ignoring `KeyboardInterrupt`, and signals and type annotating `logger.exception` as `NeverRaises`. 95% is still better than 0%.

Re: What's New in Python 3.12

#95

I've been using python for the past 10+ years, and I've got to say that the new Syntactic formalization of f-strings (PEP 701) has got to be one of the most "huh?" changes I've seen in a while. Was this such a big problem? In my experience, the GIL, faster start-up times are so much higher on the totem pole, why this now?

Yeah, I find it a bit telling that they had to show completely ridiculous toy examples:

>f"""{f'''{f'{f"{1+1}"}'}'''}"""

Re: What's New in Python 3.12

#96
post #85

PEP 695 is great. I've been using mypy every day at work in last couple years or so with very strict parameters (no any type etc) and I have experience writing real life programs with Rust, Agda, and some Haskell before, so I'm familiar with strict type systems. I'm sure many will disagree with me but these are my very honest opinions as a professional who uses Python types every day: * Some types are better than no…

> the time raises "KeyError" should actually be typed "Raises[T, KeyError]" You can't do this in Python your bucket will always have hole you can't plug. Arbitrary exceptions can appear anywhere in your code thanks to signal handlers. KeyboardInterrupt is the one you probably know without knowing. Exceptions can even come from higher in the stack down to you with the .throw method on generators.

Yep, I'm aware of these, I wrote about my thoughts about them here: https://news.ycombinator.com/item?id=37934604

Re: What's New in Python 3.12

#97
post #71

I suspect people will use these comments to share their wishlist of Python features, so let me add that I really wish Python had a safe navigation operator, for when you are dealing with nested objects that could be None. I have been trying to parse a lot of XML and JSON in Python lately and a feature like that could really help reduce boilerplate checks. https://en.wikipedia.org/wiki/Safe_navigation_operator

That's something I've wished for a long time that it had. I know you can use exceptions to get similar behavior but it's really ugly and I just generally don't like raising exceptions for cases that aren't actually exceptional (even though I know Python uses exceptions for normal flow with StopIteration). What's actually a bit odd about Python missing that operator is that its `or` operator acts as a rough equivalent…

> What's actually a bit odd about Python missing that operator is that its `or` operator acts as a rough equivalent of C#'s null-coalescing (`??`) operator.

Python `or` is C# `||` plus type coercion. It is not even roughly `??` because important non-None Python values are falsey (0, False, empty collections).

Re: What's New in Python 3.12

#98
post #71

Earlier quoted context omitted.

That's something I've wished for a long time that it had. I know you can use exceptions to get similar behavior but it's really ugly and I just generally don't like raising exceptions for cases that aren't actually exceptional (even though I know Python uses exceptions for normal flow with StopIteration). What's actually a bit odd about Python missing that operator is that its `or` operator acts as a rough equivalent…

> What's actually a bit odd about Python missing that operator is that its `or` operator acts as a rough equivalent of C#'s null-coalescing (`??`) operator. Python `or` is C# `||` plus type coercion. It is not even roughly `??` because important non-None Python values are falsey (0, False, empty collections).

    > python3 -c 'print(None or "hello")'
    hello
It evaluates to the left if that's truthy otherwise it evaluates to the right, similar to how `??` evaluates to the left if that's non-null otherwise the right.

In C# even if `||` automatically coerced the types, the output will always be a bool.

Re: What's New in Python 3.12

#99
post #43

Earlier quoted context omitted.

Of course this only works at one level and not arbitrarily deeply, but you still need to check for None with this code; it may actually be better to write `x.get("key") or {}` so that you always get an empty dict. I write 'may' because the difference between None and an empty dict may be very subtle and rarely does the API specify with enough precision what are supposed to be the semantics of each case.

> x.get("key") or {} This has the side effect of replacing falsy values like False or 0 with an empty dictionary instead of giving you the actual value. For the exact intended behaviour, you do need to explicitly check for None instead of using a short circuit trick with or.

The problem was underspecified, but I suggested that under the assumption that the value would be an Optional[dict]. If you have another falsy value, it means either Optional[Any] or something like Optional[Union[dict, list]] (I put list as an example, but you get the idea).

I would say the only reasonable choice is Optional[dict], in which case it should be sufficient, but Python being Python, it could be anything. And in these cases you need to handle all cases way more carefully.

Re: What's New in Python 3.12

#100

Earlier quoted context omitted.

Exceptions are always handled: Python exits while telling you about the exceptional situation. If you’re saying that I must handle an exception in my code rather than crash because my “fail early, fail often” design choices offend your religious preferences… then keep it to yourself and out of PEPs.

No I'm not saying that at all , I'm just saying that if you need a function to handle all exceptions, the type system should be powerful enough to express that. E.g. in a webserver if you have a handler that needs a wrapper like: def wrapper(): try: return handler() except Exception: logger.exception("unknown exception") webserver.status = 500 the type system needs to be able to determine that "f doesn't raise an exc…

> I'm just saying that if you need a function to handle all exceptions, the type system should be powerful enough to express that.

I disagree, in part because “handles all exceptions” is a lie; exceptions can occur at any point, including in exception-hnadling code.

It is not possible to have a Python function which provides the guarantee you want, so it makes no sense to have a Python type system which expressed it: it will either be never used or a lie.

If you think you need this guarantee, you need to step back and ask what the functional requirement actually is and find a different way of meeting it.

Post reply on HN