←back to thread

317 points est | 1 comments | | HN request time: 0.259s | source
Show context
oooooof ◴[] No.17448560[source]
What is it? The link points to a discussion more deep than I’m willing to read.
replies(10): >>17448567 #>>17448570 #>>17448571 #>>17448572 #>>17448575 #>>17448579 #>>17448584 #>>17448591 #>>17448617 #>>17448638 #
est ◴[] No.17448572[source]
It's a controversial PEP https://www.python.org/dev/peps/pep-0572/ which allows you to write Python like this:

    def foo():
        if n := randint(0, 3):
            return n ** 2
        return 1337


    [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
replies(7): >>17448580 #>>17448633 #>>17448694 #>>17448731 #>>17448946 #>>17449000 #>>17449023 #
stfwn ◴[] No.17448946[source]
This immediately looks useful for things like:

    if foo := bar[baz]:
        bar[baz] += 1
        return foo
    else:
        bar[baz] = 1
        return 0
Where foo is a dict keeping track of multiple things, and a non-existing key (baz) is never an error but rather the start of a new count. Faster and more readable than

    if baz in list(bar.keys()):
    ....
Similar to Swift’s ‘if let’, it seems.
replies(4): >>17448968 #>>17449008 #>>17449051 #>>17449074 #
antoinealb ◴[] No.17449008[source]
As pointed, you can use either a default dict or just simply, and [more pythonic](https://blogs.msdn.microsoft.com/pythonengineering/2016/06/2...):

    try:
      bar[baz] += 1
    except KeyError:
      bar[baz] = 1
Also you can check if a key is in a dict simply by doing "if baz in bar" no need for "list(bar.keys())", which will be slow (temp object + linear scan) vs O(1) hashmap lookup.
replies(3): >>17449075 #>>17449181 #>>17449409 #
1. bocklund ◴[] No.17449409[source]
Alternatively

`bar[baz] = bar.get(baz, 0) + 1`

One line and no error checking.

But the OP was probably just illustrating a basic example where you might have some more intense logic