2
\$\begingroup\$

I'm focusing on trying to write clean, modular Python 2.7.5 code.

def main():
  type = sys.argv[1]
  dataPatient = parseJSONFile(fileName)

  if(type == "type 1"):
    patient = [d['patient_family_member_id'] for d in dataPatient if d['id'] == sys.argv[2]]
    displayList(flatten(patient), "Msg1")

  elif(type == "type 2"):
    doctor = [d['doctor_id'] for d in dataPatient if sys.argve[2] in set(d['patient_id'])]
    displayList(doctor, "Msg2")

  elif(type == "type 3"):
    dataDoctor = parseData(fileName2)
    doctor = [d['doctor_id'] for d in dataDoctor if sys.argv[2] in set(d['year_graduated'])
    #notice this is doing nearly the same thing as the "type 1" case for each doctor
    patient = [d['patient_family_member_ids'] for d in doctor for p in dataPatient if d == p['doctor']]
    displayList(flatten(patient), "Msg3")

  elif(type == "type 4"):
    patient = [d['patient'] for p in dataPatient if sys.argv[2] in set(d['age'])
    displayList(flatten(patient), "Msg4")

Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. I'm trying to make this code easy for someone to read and add more cases. What is the best way of avoiding a lot of the repetition in this code?

\$\endgroup\$
1

1 Answer 1

1
\$\begingroup\$

First things first: while this obviously comes from real code, the way you "anonymized" your code doesn't work, eg. sys.argve doesn't exist.

I'm trying to make this code easy for someone to read and add more cases.

If you want Python developers to be able to read your code easily, please follow PEP 8 (using a tool such as pep8). That includes sticking to 80 columns, using underscored_names and using ALL_CAPS variables for constant strings.

Most of this code in the if else statements are very similar. I feel like I might be able to use a lambda to clean this code up but I'm not sure that will work. What is the best way of avoiding a lot of the repetition in this code?

Without having tried to improve your code yet, using list comprehensions and lambdas is a good way to shorten code, but short code != readable code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.