Why couldn't Python use the `as` keyword to do assignment expressions?

79 Views Asked by At

Python 3.8 introduced the "walrus operator" := to do assignment expressions. I assume they considered using the keyword as but rejected it. Are there existing syntactic cases for as that precluded using it for assignment expressions?

To use an example from the Python docs:

# Actual Python 3.8 syntax
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

# Why not this?
if (len(a) an n) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

Here's another example:

# Actual Python 3.8 syntax
while (block := f.read(256)) != '':
    process(block)

# Why not this?
while f.read(256) as block:
    process(block)
2

There are 2 best solutions below

1
Samwise On BEST ANSWER

Insight into questions like these ("why did they do X instead of Y") can usually be gained by reading the relevant PEP, which often has a section on "things we considered but rejected".

https://peps.python.org/pep-0572/#alternative-spellings

EXPR as NAME: stuff = [[f(x) as y, x/y] for x in range(5)] Since EXPR as NAME already has meaning in import, except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

The page goes on to list other reasons that using as in this way was considered to be potentially confusing.

0
murat taşçı On

In python the as keyword is already heavily used for other functionalities, such as aliasing in import statements, exception handling, and with context managers. Overloading the as keyword to also handle assignment expressions would introduce ambiguity and complexity in parsing Python code.

A. Alias in imports: import numpy as np

B. Exception handling: except Exception as e

C. Context managers: with open("file.txt") as f

Using as for assignment expressions could create confusion when reading the code. It would be challenging to quickly distinguish whether as is being used for aliasing, exception handling, with a context manager, or for assignment expressions.

The walrus operator := was introduced to clearly demarcate assignment expressions, making it easier to understand the intent of the code. It allows for concise and unambiguous code, which aligns with Python's philosophy of readability and simplicity.