Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign and check a variable in a single line in Python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Till Python 3.8, there was no way to do this, as statements in Python don’t have a 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:
   ....
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading