I’m trying some optimisation on my code and I struggle with multiple if then statements. The point is to update SQL database with psycopg2 and I must set some variables with “None” to be “null” in SQL.
If I do if/elif/elif, the script will leave on the first valid condition but I want every condition to be checked, here is the script :
if variable_a == "": variable_a = None if variable_b == "": variable_b = None if variable_c == "": variable_c = None if variable_d == "": variable_d = None
Is there a way to do it in one row such as assigning multiple variable values?
variable_a, variable_b, variable_c, variable_d = "", "", "", ""
Bonus question : the whole point of the script is to srap data from website, getting the desired data with ReGex then updating SQL databases. The full script is about 24.000.000 iterations with all the code inside a “for i in” loop, i’m looking for a way to optimize it because it takes actually 12 days running… Do you have any tips ? Libraries ?
Thanks in advance! :)
Advertisement
Answer
You can define a simplified function for that case:
var_a, var_b, var_c, var_d = "", "", "", "" to_None = lambda v: None if v == "" else v var_a, var_b, var_c, var_d = to_None(var_a), to_None(var_b), to_None(var_c), to_None(var_d) print(var_a, var_b, var_c, var_d)
None None None None