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

Python – Only if statement and no else statement on 1 line

Question:

I know it’s possible to just put an if statement on one line but is there a way to do it so that PEP8 doesn’t reformat it to be on two lines? I know that you can put it on two lines but that doesn’t answer my question about the possibility of putting it on one line.

Attempts:

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

if date > p1_max_date: p1_max_date = date

The above code works except for the fact that PEP8 reformats it to this:

if date > p1_max_date:
            p1_max_date = date

I know that I can turn off the auto-format feature on save, but is there a way to achieve the same functionality on one line (only execute the statement if the if condition is true without having an else statement) without turning off the PEP8 reformat on save feature?

I was thinking of something along the lines of:

p1_max_date = date if date > p1_max_date

But this gave me a syntax error:

File "<string>", line 1
    p1_max_date = date if date > p1_max_date
                                           ^
SyntaxError: invalid syntax

I also tried using the ternary operator but neither of the following attempts work:

p1_max_date = date if date > p1_max_date else pass
# this doesn't work and gives me a syntax error
p1_max_date = date if date > p1_max_date else None
# this doesn't work because I don't want to change the value of the variable if the condition is false

>Solution :

p1_max_date = date if date > p1_max_date else p1_max_date

should do it.
Depending on the data type of date and p1_max_date, you might also use

p1_max_date = max(p1_max_date, date)

, which is probably the easier to read solution.

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