2

Is there a way in Python to use a function result both as a test of an if statement and as the value inside the statement? I mean something like:

if f(x) as value:
   # Do something with value

Not

value = f(x)
if value:
   # Do something with value

or

with f(x) as value:
   if value:
       # Do something with value
aminography
  • 21,986
  • 13
  • 70
  • 74
  • 1
    In `python3.8` Yes. By making use of the infamous `walrus` operator. `if value := f(x):..# do_stuff(value)` – han solo Nov 06 '19 at 07:10

2 Answers2

2

Yes, as of python3.8 and in later releases, there is. By making use of the controversial walrus(:=) operator like,

$ python3.8
Python 3.8.0 (default, Oct 15 2019, 11:27:32) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x): return x
... 
>>> if value := f(1):
...   print(value)
... 
1
>>> if value := f(0):
...   print(value) # won't execute
... 
>>> 
han solo
  • 6,390
  • 1
  • 15
  • 19
0

As of the new python 3.8, you can use:

if value := f(x): 
    # Do something with value
U13-Forward
  • 69,221
  • 14
  • 89
  • 114