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

Is there a way to combine statements if & as in python?

I have been just wondering if it is possible to somehow combine ‘if’ and ‘as’ statements like this:

if possible_error() as error:
  return error

instead of

error = possible_error()
if error:
  return error

where ‘possible_error’ function returns either empty string or error message. By doing so I could save one line of code.

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

I know that some compromise is to run this function twice:

if possible_error():
  return possible_error()

but I would rather avoid doing this.

>Solution :

This is what the relatively new "walrus" operator is for:

if (error := possible_error()):
    return error
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