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

Denis Krienbühl denis at href.ch
Thu Sep 7 06:43:13 EDT 2017


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 :)

Cheers,

Denis



More information about the Python-ideas mailing list