Thursday, 4 January 2024

django python ternaray operator not working optimally

 In Js or many other lauages u have

a = (condition = true) ? truth : false


in python, you can mimic this by using a tuple

a = (falseCondition, truCondition) [bool(condition = true)]


this is not recommended , recommended is to use

if :

else:


because your falseCondition truCondition will be evalualted first, if they have issue you will have error first before evaluation of bool


for example

time_obj= (yesterday_obj, datetime.strptime(my_might_be_empty_value_str, '%Y-%m-%d %H:%M:%S'))[bool(my_might_be_empty_value_str)]


this will neve work cause strptime cant evaluate my_might_be_empty_value_str when my_might_be_empty_value_str is empty , 

No comments:

Post a Comment