2

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]
Charlie Morton
  • 737
  • 1
  • 7
  • 17
  • Possible duplicate of [Can we have assignment in a condition?](https://stackoverflow.com/questions/2603956/can-we-have-assignment-in-a-condition) – Pierre V. Oct 03 '19 at 16:01
  • So the `answer` should stay undefined when `get_something()` returns None? – ababak Oct 03 '19 at 16:04
  • @ababak yes, well not undefined it should be None – Charlie Morton Oct 03 '19 at 16:04
  • 1
    that's wrong: 1) one-lier will not make your case to be more readable 2) you don't have to call first function twice 3) and `answer` should not stay undefined in case of any potential references to it – RomanPerekhrest Oct 03 '19 at 16:06

3 Answers3

3

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:

2

We can in Python 3.8 with assignment expressions:

if (result := get_something()) is not None:
    # do something with result
jfaccioni
  • 7,099
  • 1
  • 9
  • 25
0

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
>>>
CristiFati
  • 38,250
  • 9
  • 50
  • 87