Hacker News new | ask | show | jobs
by sgarland 753 days ago
For a simple example, I think the walrus operator (:=) could be considered clever. I like it, and use it, but the fact that you can declare a variable, store a value in it, and then perform actions depending on its value, all in one line, gives me pause.

    if (foo := bar()) is not None:
        baz(foo)
Whereas the traditionally accepted Python method of dealing with this would be EAFP:

    try:
        foo = bar()
        baz(foo)
    except AttributeError:
        # handle exception
2 comments

What? Those aren't equivalent at all.

Where are you expecting an AttributeError to come from? Why are you comfortable catching them from anything inside of the baz(...) invocation?

The traditional method would be to just bind it and check for a null outside the expression.

    foo = bar()
    if foo is not None:
        baz(foo)
I don't know why people insisted on pretending binding variables before using them was such a difficulty that it was worth altering the language. Lazy and bad programmers aren't going to stop being lazy and bad when you hand them the ability to name things willy nilly. They'll just use that badly as well.
The assumption in the example is that baz() required foo to not be None; attempting to use None where you expect a string will probably in an AttributeError.

As to your example, both LBYL and EAFP are accepted Python standards.

In your first example I think most people would skip the 'is not None' as None is already falsy and drop the extra braces.

I find it visually clearer than the second example where the cause and effect are slightly separated, but I do agree there's an element of cleverness to it.

But that would be a mistake if you need the branch to run for other falsely values like 0 or the empty string.
In this imaginary example, yes, a False is likely to cause the same issues that None would. But as a sibling comment mentions, it’s not always desirable to drop the explicitness for syntactic sugar.