0

This might be a silly question, but I am wondering if there is a way to print or use the value being evaluated in an if statement without having to store it in a variable first before evaluating it?

something similar to this sort of syntax:

if value_of_really_long_expression == True: print(value_of_really_long_expression) 

of course this can be achieved by:

x = value_of_really_long_expression if x == True: print(x) 

purely out of interest/curiosity, I am wondering if this is even possible

2
  • Nope, not in the stable releases of python in any case. Though irony being, if you entered the if block on an == check, you already know what the expression evaluated to. However, i'm assuming this is just a glorified simplified example. Commented Aug 27, 2019 at 12:41
  • 1
    You may be interested in this post: stackoverflow.com/q/11880430/4636715 . At least you can reduce to a one-liner. Commented Aug 27, 2019 at 12:42

1 Answer 1

3

It's not possible; there are no implicit references one could use. Python 3.8, though, introduces an assignment expression which at least streamlines the assignment:

if (x := really_long_expression): print(x) 

The scope of x remains the same as if you had written

x = really_long_expression if x: print(x) 

that is, x is not local to the body of the if statement.

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

3 Comments

awesome...was not aware of this - waiting to accept answer (Time limit) :)
Strictly speaking, you have to wait a few months yet before being able to use this officially anyway :)
understood, but excited for 3.8 :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.