|
⇤ ← Revision 1 as of 2026-03-20 01:07:14
Size: 753
Comment:
|
Size: 1133
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 4: | Line 4: |
TODO: check out presentation from PyCon 2019 introducing it. |
|
| Line 36: | Line 34: |
| }}} | |
| Line 37: | Line 36: |
| From [[https://dustingram.com/talks/2019/04/04/the-walrus-operator/|PEP 572: The Walrus Operator [Pycon 2019]]]: | |
| Line 38: | Line 38: |
| {{{#!highlight python numbers=off # Instead of: |
|
| Line 39: | Line 41: |
| y = f(x) foo = [] if y: foo = [y, y**2, y**3] # use foo = [y := f(x), y**2, y**3] ### # Instead of results = [] for x in data: r = f(x) if r : results.append(result) # use results [ y for x in data if (y := f(x)) ] |
Python Walrus operator
Good examples of the Python walrus operator.
From: https://www.reddit.com/r/Python/comments/1rw18i5/comment/oaxdl2e/
# perfect for re.match
if has_whatever := re.match(stuff)
a, b = has_whatever.groups()
###
only call other_function if res is some value
if (result := some_fun()) in ("a", "b"):
other_function(res)
###
# conditional based on the result of res
if func(res := gfunc()):
# use res safely
###
while line := fp.readline():
...
###
if bad := [r for r in records if r.bad()]:
raise ValueError('Bad records: ' + ', '.join(b.name for b in bad))
From PEP 572: The Walrus Operator [Pycon 2019]:
# Instead of:
y = f(x)
foo = []
if y:
foo = [y, y**2, y**3]
# use
foo = [y := f(x), y**2, y**3]
###
# Instead of
results = []
for x in data:
r = f(x)
if r :
results.append(result)
# use
results [
y for x in data
if (y := f(x))
]