Reputation: 111
Is there a way to improve this code to make it shorter?
if date_a is None and date_b is None and date_c is None:
start_date = current_date
else:
if date_a is not None:
start_date = date_a
elif date_b is not None:
start_date = date_b
elif date_c is not None:
start_date = date_c
Upvotes: 1
Views: 2471
Reputation: 69276
As an alternative in Python >= 3.8 you can use an assignment expression plus any()
:
any(start_date := d for d in (date_a, date_b, date_c, current_date))
In your specific case I suspect that a chain of or
would be faster, however any()
will also work well if you have a collection of variables and not just single variables with different names:
any(start_date := d for d in dates)
The return value of any
will let you know whether there was some truthy value or not.
Upvotes: 2
Reputation: 4674
First, you can remove one if/else depth:
if date_a is not None:
start_date = date_a
elif date_b is not None:
start_date = date_b
elif date_c is not None:
start_date = date_c
else:
start_date = current_date
You could also take advantage of the for...else
statement:
for start_date in (date_a, date_b, date_c):
if start_date is not None:
break
else:
start_date = current_date
The else
only happens if none of the break
conditions triggered, e.g. if all of the potential start_date
's were None
.
Upvotes: 1
Reputation: 95908
You can do something like:
start_date = date_a or date_b or date_c or current_date
Alternatively, there really is nothing wrong with:
if date_a is not None:
start_date = date_a
elif date_b is not None:
start_date = date_b
elif date_c is not None:
start_date = date_c
else:
start_date = current_date
Upvotes: 0
Reputation: 71444
You can use or
, which will give you the first truthy value:
start_date = date_a or date_b or date_c or current_date
Another solution would be to turn them into an iterable, add an is None
filter, and pull the first item using next()
:
start_date = next(date for date in (
date_a,
date_b,
date_c,
current_date
) if date is not None)
This approach works better if you need a condition other than "truthiness", or if you have a lot of values (in which case organizing them in an iterable container is likely easier than pasting them into a long or
sequence).
Upvotes: 2