How does EK9's := differ from Python's := walrus operator?
← Getting Started · Ref: Q986
EK9's := and Python's := (walrus) look identical but behave completely differently.
PYTHON := (walrus) is an ASSIGNMENT EXPRESSION:
- Assigns a value AND evaluates to that value
- Can be used INSIDE conditions: if (n := len(data)) > 3:
- Creates the variable on first use
- Returns the assigned value for further use in the expression
EK9 := is an ASSIGNMENT STATEMENT:
- Assigns to an EXISTING variable (must be declared first with <-)
- Cannot be used inside expressions or conditions
- Does not return a value
- Is a standalone statement only
TO ASSIGN AND TEST IN EK9:
Use the <- guard declaration, not :=
if n <- computeLength() use(n)
The guard declares n AND checks if it is set. This is EK9's equivalent of Python's walrus pattern, but uses <- not :=.
QUICK REFERENCE:
Python: if (n := len(data)) > 3: walrus assigns + evaluates EK9: if n <- computeLength() then n > 3 guard declares + checks isSet
Python: x := 5 (inside expression) walrus, creates variable EK9: x <- 5 (standalone) declaration, creates variable EK9: x := 5 (standalone) assignment, updates existing variable
Example
defines module qa.gettingstarted.walrusvsassign defines function computeLength() as pure -> items as List of String <- rtn as Integer: items.length() defines program WalrusVsAssignDemo() stdout <- Stdout() words <- ["hello", "world", "ek9", "language"] minimumSize <- 2 // EK9 guard pattern (replaces Python walrus in conditions) if wordCount <- computeLength(words) then wordCount > minimumSize stdout.println(`Has ${wordCount} words - enough to process`) // := is for updating existing variables (standalone statement only) message <- "initial" message := "updated" stdout.println(message) // <- declares, := updates — both are STATEMENTS, never expressions counter <- 0 counter := counter + 1 stdout.println(`Counter: ${counter}`)
Common mistakes
E01010 — EK9's := is a statement, not an expression. It cannot be used inside conditions. Use the <- guard pattern: 'if v <- expr() then condition'.
Incorrect:
if (wordCount := computeLength(words)) > minimumSize stdout.println(`Has ${$wordCount} words - enough to process`)
Correct:
if wordCount <- computeLength(words) then wordCount > minimumSize stdout.println(`Has ${wordCount} words - enough to process`)
Other ways to ask this
- Is EK9's := the same as Python's walrus operator?
- Can I use := inside an if condition in EK9?
- Why can't I write 'if n := getValue()' in EK9?
- How do I assign and test a value in one step in EK9?
Coming from another language?
Python developers moving to EK9: your := walrus patterns become <- guard expressions. EK9's := only works as a standalone statement for updating existing variables.
Keywords: statement, walrus, condition, guard, assign, expression