Python Forum
if <expr> as <name> syntax interest
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if <expr> as <name> syntax interest
#1
A useful addition to the python base is an if statement that can capture the expression's result in a variable if it's truthy:
if re.match(pattern, str) as match:
	print(match.group(0))
Which could replace some current uses of this pattern:

match = re.match(patter, str)
if match:
	print(match.group(0))
# damages readability if match is only needed inside the if
I know the if doesn't introduce a new scope (variables defined inside the if can be referenced outside),
but if the result of the expression is only valuable when it's not falsy then this syntax expresses it more cleanly.

An alternative pattern that would entirely be replaced:
if re.match(pattern, str):
	match = re.match(patter, str)
	print(match.group(0))
# damages maintainability because any changes will need to be applied twice
# also it's less efficient
Would people be interested in this feature and is it PEP-able? I haven't found any PEP proposals related to this.
Reply
#2
actually, I think you mean assignment expressions - PEP572 and it was officially accepted
https://www.python.org/dev/peps/pep-0572/
https://www.reddit.com/r/Python/comments...fficially/
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks for the link! That covers my use cases, although I prefer as over :=...

Apparently why they didn't use as over := is discussed here: https://www.reddit.com/r/Python/comments...ly/e1pfzgv

Quick snippet:
Quote:The reason why they didn't is because this had to work in logical expressions, and from a parsing standpoint, it would be extremely difficult to determine the assignment expression in the context manager of a comprehension containing the expression, and the assignment of the context manager itself.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020