Home > Software engineering >  Only if statement and no else statement on 1 line
Only if statement and no else statement on 1 line

Time:03-18

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:

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

CodePudding user response:

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.

  • Related