Tuesday, June 18, 2019

Being more pythonic with the shortcut conditional : A if C else B

I had these two blocks of "if else" code that I found too crude.

test_case_data = None
test_case_data2 = None

if test_already_exists(tests_object_list, test1_name) is not None:
  print(">>>> Test 1 already exists. skipping the add")
else:
  print(">>>> Test 1 doesn't exist. adding")
  test_case_data = add_test_case(api_conn, int(project_id), test1_name)

if test_already_exists(tests_object_list, test2_name) is not None:
  print(">>>> Test 2 already exists. skipping the add")
else:
  print(">>>> Test 2 doesn't exist. adding")
  test_case_data2 = add_test_case(api_conn, int(project_id), test2_name) 
 

I took the code and applied Guido's "ternary solution," Link here.

 
All of the above code became three-four lines of code and I was able to apply a one-line Pythonic truthy and falsy evaluation on the return object. Very lambda-ish. 


[Correction: What I had earlier with data = func_call if True else other_func_call, was incorrect. Corrected below. So it's really A if A (when A is not None) else B (which in this case creates a new test case object.]

for current_test in tests_lists:
  test_exists_data = test_already_exists() # Note returns None or or existing test data
  test_case_data = test_exists_data if test_exists_data else add_test_case()


  ...further code that doesn't contribute to A if C else B 
 
As a side note: This same elegance in code I also found with the use of the "with," statement using the Context Manager. But for this, a lot more compact, readable and Pythonic.

No comments:

Exploring ELK (Elastic) Stack for hack-a-thon

At my current gig, our group finally got to do hack-a-thon week and I joined a team project that tied together a few of the technologies I&#...