[Python-ideas] if <expression> as <variable>

Jason H jhihn at gmx.com
Thu Sep 7 10:36:40 EDT 2017



> Sent: Thursday, September 07, 2017 at 6:43 AM
> From: "Denis Krienbühl" <denis at href.ch>
> To: python-ideas at python.org
> Subject: [Python-ideas] if <expression> as <variable>
>
> Hi!
> 
> I’ve been having this idea for a few years and I thought I finally see if what others think of it. I have no experience in language design and I don’t know if this is something I’ve picked up in some other language. I also do not know what the ramifications of implementing this idea would be. I just keep thinking about it :)
> 
> I quite often write code like the following in python:
> 
> 	result = computation()
>        if result:
>             do_something_with_computation(result)
> 
> More often than not this snippet evolves from something like this:
> 
>       if computation():
>> 
> That is, I use the truthiness of the value at first. As the code grows I refactor to actually do something with the result.
> 
> What I would love to see is the following syntax instead, which to me is much cleaner:
> 
>    if computation() as result:
>        do_something_with_result(result)
> 
> Basically the result variable would be the result of the if condition’s expression and it would be available the same way it would be if we used my initial snippet (much the same way that the result of with expressions also stays around outside the with-block).
> 
> Any feedback is appreciated :)

I also often wonder why we are left doing an assignment and test. You have two options:
1. assign to a variable then test and use
2. repeat the function call

I would offer that 'with' [sh|c]ould be used:
with test() as x:
   handle_truthy(x)
else:
   handle_falsey() # do we provide x here too? Because None vs False?




More information about the Python-ideas mailing list