0

Is it possible to "re-use" the value of a parameter of an if-clause?

I have a function that returns either True or a dictionary:

def foo():
    if random.randint(0, 1) == 0:
        return True
    else:
        return {"time": time.time()}

If foo() returns the dictionary, I also want to return it. If foo() returns True I want to just continue.

Currently I'm using:

if_value = foo()

if if_value is not True:
    return if_value

My goal would be to avoid saving the return value of the function into a variable, because it makes my code really ugly (I need to do this about 20 times in a row).

When using a Python shell, it seems to work like this:

if function_that_returns_True_or_an_int() is not True:
    return _

Any suggestions about this?

9
  • 2
    So you're trying to save the value of an expression without saving the value of the expression as a variable? Commented Nov 29, 2021 at 14:01
  • I don’t see a function statement Commented Nov 29, 2021 at 14:02
  • 1
    It's hard to really answer without some more context because the answer is going to really depend on your use-case. What happens if the condition is not true? There is a return there but no function. Please provide a minimal reproducible example so it is easy to understand the scenario. For example, you might be able to do something like return func() or some_value, but again - it is hard to say without a proper minimal reproducible example Commented Nov 29, 2021 at 14:05
  • 3
    Also, what Python version are you using because the walrus operator might be exactly what you need (Python 3.8 onwards) Commented Nov 29, 2021 at 14:10
  • 1
    Well, to be honest your edit didn't really fix what (to me) is the real problem. foo itself was less important, more important is what you do with it which is currently not clear. You do return value in case the value is not true, but what is the else? What is the function this return belongs to? Knowing this will allow to offer other solutions apart from using the walrus (maybe ones that remove the need of a condition altogether) Commented Nov 29, 2021 at 17:27

1 Answer 1

1

You can use the walrus operator (:=) to declare a variable and assign to it, then do your comparison

if (x := your_function()) == condition:
    # something
else:
    # something else

print(x)  # x is still a named variable and in scope
Sign up to request clarification or add additional context in comments.

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.