Questions tagged [walrus-operator]

The "walrus operator" is an informal term for the assignment expression syntax (a := b) that were proposed in PEP 572 and introduced in Python 3.8

After acceptance of PEP 572, introduced assignment expressions, which are a way to assign to variables within an expression using the notation NAME := expr. Given the resemblance between := and an emoticon of eyes plus walrus tusks, the syntax is sometimes known as the "walrus operator", a term coined in the PEP.

Use and/or with it for increased visibility.

49 questions
20
votes
2 answers

Python Walrus Operator in While Loops

I'm trying to understand the walrus assignment operator. Classic while loop breaks when condition is reassigned to False within the loop. x = True while x: print('hello') x = False Why doesn't this work using the walrus operator? It ignores…
19
votes
2 answers

Walrus operator in list comprehensions (python)

So when coding I really like to use list comprehensions to transform data and I try to avoid for loops. Now I discovered that the walrus operator can be really handy for this, but when I try to use it in my code it doesn't seem to work. I've got the…
Jeroen Vermunt
  • 672
  • 1
  • 6
  • 19
15
votes
2 answers

How to type hint with walrus operator?

I am trying to type hint a walrus operator expression, i.e. while (var: int := some_func()): ... How can I do this?
rkoni
  • 151
  • 3
15
votes
2 answers

Why can't Python's walrus operator be used to set instance attributes?

I just learned that the new walrus operator (:=) can't be used to set instance attributes, it's supposedly invalid syntax (raises a SyntaxError). Why is this? (And can you provide a link to official docs mentioning this?) I looked through PEP 572,…
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
13
votes
2 answers

What is the correct syntax for Walrus operator with ternary operator?

Looking at Python-Dev and StackOverflow, Python's ternary operator equivalent is: a if condition else b Looking at PEP-572 and StackOverflow, I understand what Walrus operator is: := Now I'm trying to to combine the "walrus operator's assignment"…
10
votes
2 answers

walrus operator in dict comprehension

I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator: >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in…
10
votes
1 answer

Why does "if not a := say_empty()" raise a SyntaxError?

PEP 572 introduces the assignement operator ("walrus operator"). The following code works, and outputs empty def say_empty(): return '' if a := say_empty(): print("not empty") else: print("empty") I tried to negate the condition: def…
WoJ
  • 27,165
  • 48
  • 180
  • 345
7
votes
1 answer

Order of evaluation of assignment expressions (walrus operator)

I have the following expression: >>> a = 3 >>> b = 2 >>> a == (a := b) False Now, a == 2 after the operation, as expected. And the result is what I would want, i.e., comparison of a to RHS of assignment before assignment. Reversing the order of the…
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
7
votes
1 answer

Using a walrus operator in if statement does not work

I have a simple function that should output a prefix based on a pattern or None if it does not match. Trying to do a walrus it does not seem to work. Any idea? import re def get_prefix(name): if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$',…
Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29
6
votes
2 answers

Two Walrus Operators in one If Statement

Is there a correct way to have two walrus operators in 1 if statement? if (three:= i%3==0) and (five:= i%5 ==0): arr.append("FizzBuzz") elif three: arr.append("Fizz") elif five: arr.append("Buzz") else: arr.append(str(i-1)) This…
6
votes
1 answer

Why does using the walrus operator on a member variable raise a SyntaxError?

Why can't I use the walrus operator := to assign to an attribute? It works when assigning to a local variable: my_eyes = ["left", "right"] if saved_eye := my_eyes.index("left"): print(saved_eye) # outputs >>> 0 But it is a syntax error if I…
Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38
5
votes
1 answer

Can you combine the addition assignment ( += ) operator with the walrus operator ( := ) in Python?

This is the code I write right now: a = 1 if (a := a + 1) == 2: print(a) I am wondering if something like this exists: a = 1 if (a +:= 1) == 2: print(a)
Nathan Dai
  • 392
  • 2
  • 11
5
votes
3 answers

How to check if the Enter key was pressed while using the Walrus operator in Python?

I'm trying to get input from a user using the Walrus operator :=, but if the user will only type in the Enter key as input, than the python script will terminate. How can I catch this error and make sure that the user hasn't only pressed the Enter…
MendelG
  • 14,885
  • 4
  • 25
  • 52
3
votes
1 answer

Unpack a tuple and assign a variable to the second value only if the first value is truthy

I have a Python function which returns a tuple with a boolean and string def check_something(): # ... return bool_value, str_messsage Is there a way I can use the output of this function in an if statement using the boolean and assign the…
Midhun Mathew Sunny
  • 1,271
  • 4
  • 17
  • 30
3
votes
2 answers

How can named expressions be interpreted in f-strings?

I am trying to use named expressions inside a f-string: print(f"{(a:=5 + 6) = }") Returns: (a:=5 + 6) = 11 But I am hoping for something like this: a = 11 Is that possible, by combining the walrus operator and f-strings (so that I don't have to…
1
2 3 4