Perform a function on result of another function if not none

2k Views Asked by At

I have a small snippet of code with two functions in it. I want to call the first function if it receives a response then perform a function on that response. Then assign the result to another variable.

In a verbose way it looks like:

result = get_something()
if result:
    answer = transform(result)

alternatively I could do

if get_something():
    answer = transform(get_something())

but that requires calling the first function twice

is there a way to do all of this on one line a bit like a ternary (maybe as a lambda)

answer = transform(result) if get_something() else None

Obviously in the above there is nothing to state what result is but I need to say basically where result = get_something()

I can do that in a list comprehension but that seems a bit dumb

   answer = [transform(x) for x in [get_something()] if x][0]
3

There are 3 best solutions below

0
Arno Maeckelberghe On BEST ANSWER

In the latest Python version (Python 3.8) there's a new assignment that may be useful for you, :=:

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “walrus operator” due to its resemblance to the eyes and tusks of a walrus.

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

In this example, the assignment expression helps avoid calling len() twice:

0
jfaccioni On

We can in Python 3.8 with assignment expressions:

if (result := get_something()) is not None:
    # do something with result
0
CristiFati On

Although I don't fully understand the reasons for doing things this way (which is less clear than any of the others), here's an example using lambda:

>>> def get_something(flag):  # Added the flag argument, to mimic different return values
...     return 5 if flag else None
...
>>> answer = (lambda func, arg: func(arg) if arg else None)(int, get_something(True))
>>> answer
5
>>> answer = (lambda func, arg: func(arg) if arg else None)(int, get_something(False))
>>> answer
>>>