Hacker News new | ask | show | jobs
by Kwpolska 1216 days ago
Python’s scoping rules are wonky, but the walrus is generally useful in two cases. The first one is to define a variable in an `if` and only run the contents of the `if` if the variable is truey — for example, re.search returns a Match object or None:

    if (m := re.search("regex is(n't)? fun")):
        print("there was a match")
        # do something with m
The other would be defining a variable in the `if` clause of a list comprehension and using it in the output (which is not necessary in languages where map/filter is a first-class citizen, because you could just map before you filter):

    [y for x in xs if (y := f(x)) == 5]
I can’t think of a way to define a variable in either of those cases without using the walrus and without significantly extending the code (you can define the `m` object and then do `if m:` on two lines, or you can nest two list comprehensions).
1 comments

There's also:

  while data := fh.read(131072):
    # do stuff
which is a lot nicer than:

  while True:
    data = fh.read()
    if not data: break
    # do stuff