0

Sometimes, in C, I like to assign and check a conditional variable on the same line - mostly for the purposes of self-documentation while isolating a code portion (e.g. instead of just writing if ( 1 ) { ... }), without having to write an #ifdef. Let me give an example:

#include <stdio.h>
#include <stdbool.h>

int main() {
    bool mytest;
    if ( (mytest = true) ) {
      printf("inside %d\n", mytest);
    }
    printf("Hello, world! %d\n", mytest);
    return 0;
}

This does what you'd expect: if you have if ( (mytest = true) ) {, the output of the program is:

inside 1
Hello, world! 1

... while if you write if ( (mytest = false) ) {, the output of the program is:

Hello, world! 0

(This seems like a standard technique, considering that leaving out the inner parentheses in the if might cause "warning: using the result of an assignment as a condition without parentheses [-Wparentheses]")

So, I was wondering if there is an equivalent syntax in Python?

The naive approach does not seem to work:

$ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> mytest = None
>>> if ( (mytest=True) ): print("inside {}".format(mytest))
  File "<stdin>", line 1
    if ( (mytest=True) ): print("inside {}".format(mytest))
                ^
SyntaxError: invalid syntax

... however, for a long time I also thought Python did not have a syntax for a ternary expression, but then it turned out, it has - which is why I'm asking this question.

sdbbs
  • 4,270
  • 5
  • 32
  • 87

1 Answers1

1

Till Python 3.8, there was no way to do this, as statements in Python don't have a return value, so it was invalid to use them where an expression was expected.

Python 3.8 introduced assignment expressions, also called walrus operator:

if mytest := True:
    ...

if (foo := some_func()) is None:
   ....
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504