Assignment Expressions
E256161
Assignment Expressions are a Python language feature introduced by PEP 572 that allow assigning values to variables as part of larger expressions using the “walrus” operator (:=).
All labels observed (3)
| Label | Occurrences |
|---|---|
| Assignment Expressions canonical | 1 |
| Python Language Reference – Expressions – Assignment expressions | 1 |
| walrus operator | 1 |
Statements (43)
| Predicate | Object |
|---|---|
| instanceOf |
Python language feature
ⓘ
expression construct ⓘ |
| alsoKnownAs |
Assignment Expressions
ⓘ
surface form:
walrus operator
PEP 572 ⓘ
surface form:
walrus operator (:=)
|
| author | Chris Angelico ⓘ |
| bdfLDecisionBy | Guido van Rossum ⓘ |
| bindingTime | at runtime during expression evaluation ⓘ |
| canBeUsedIn |
comprehensions
ⓘ
generator expressions ⓘ if statements ⓘ lambda expressions (with restrictions) ⓘ while statements ⓘ |
| cannotTarget | attribute references in some contexts (subject to normal assignment rules) ⓘ |
| category | Python expression syntax ⓘ |
| controversy |
PEP 572
ⓘ
surface form:
PEP 572 sparked significant discussion in the Python community
|
| designGoal |
avoid repeated expensive computations
ⓘ
improve readability in some patterns ⓘ |
| documentationSection |
Assignment Expressions
self-linksurface differs
ⓘ
surface form:
Python Language Reference – Expressions – Assignment expressions
|
| enables |
inline assignment
ⓘ
reusing computed values within an expression ⓘ |
| evaluationOrder | expression on right of := is evaluated then bound to target name ⓘ |
| example |
if (n := len(items)) > 0: print(n)
ⓘ
results = [y for x in data if (y := f(x)) is not None] ⓘ while (line := file.readline()) != "": process(line) ⓘ |
| exampleUseCase |
capturing match results from regular expressions
ⓘ
filtering and binding in list comprehensions ⓘ reading input in a while loop ⓘ |
| introducedBy | PEP 572 ⓘ |
| introducedInVersion | Python 3.8 ⓘ |
| language | Python ⓘ |
| notAllowedIn |
simple assignment target list
ⓘ
top-level of comprehension iterable expression (to avoid scoping confusion) ⓘ |
| pepNumber | 572 ⓘ |
| purpose | assign values as part of larger expressions ⓘ |
| reduces | need for separate assignment statements ⓘ |
| relatedTo |
assignment statements
ⓘ
name binding ⓘ |
| returns | assigned value ⓘ |
| scopeRule | follows normal Python scoping rules for the target name ⓘ |
| standardizedIn | Python 3 language specification ⓘ |
| status | accepted PEP ⓘ |
| syntaxForm | NAME := expression ⓘ |
| usesOperator | := ⓘ |
Referenced by (3)
Full triples — surface form annotated when it differs from this entity's canonical label.
this entity surface form:
walrus operator
this entity surface form:
Python Language Reference – Expressions – Assignment expressions