2

Is there any other code form, that one can both use a function in if statement and get the value of function without executing the function twice?

For example,

There exists a function, fun1(arg), which takes an hour to return its result (The result value can be either None or some int)

and I want to do some further calculation(for example get its squared value) only if the result from fun1 is not None.

This will be done by:

result = fun1(arg) 
if result: 
    result = result * result

Is there any shorter form such as

if (result = fun1(arg)):
    result = result * result

in python?

1
  • The first way is the standard way to do this, and doesn’t result in any more memory overhead. Commented Jul 29, 2018 at 17:14

5 Answers 5

4

It may be more "clean" in a code manner, it is possible in C/C++ to do the 2nd one. Not in Python to the best of my knowledge. Moreover, the two examples you gave have the exact same needs in term of memory and computation. So it would be totally equivalent to use any of these two.

The two are absolutely identical. So my answer would be, go with your first method that you already know how to code 👍.

Do not over complicate when it is not necessary, it is a good piece of advice in general.

Sign up to request clarification or add additional context in comments.

Comments

3

This is coming in a future version of python. See the following PEP

https://www.python.org/dev/peps/pep-0572/

It'll be known as an assignment expression. The proposed syntax is like;

# Handle a matched regex
if (match := pattern.search(data)) is not None:
    # Do something with match

Comments

0

No you can't do this. Statements in Python not work as expressions in C with ;.

Comments

0

Well the second possible solution you wrote is incorrect since the 'result' variable in the if statement has no preassigned value. I would simply go with the first one...

Comments

0

What you are trying to do in your 2nd code is assignment inside expressions, which can't be done in Python.

From the official docs

Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

also, see:

http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.