1

I am experimenting with hierarchical task planning (in python) and I would like to have functions which return lists of tasks. I need to differentiate between alternative paths and sequential tasks. My current approach is to return a list of lists of tasks, e.g.:

def travel():
    return [ [call_yellow_cab, ride_yellow_cab, pay_driver],
             [call_limousine,  ride_limousine,  pay_driver] ]

The sequential tasks would be call.., ride.., pay_driver. The first and second lists would represent alternative task sequences (cab or limousine).

As 'Explicit is better than implicit' according to 'The Zen of Python' I am curious if there is a more explicit way to differentiate between the alternative tasklists and the sequential tasks within. Or is my approach not that bad as 'Simple is better than complex.' ?

2
  • I think your current list-of-lists approach (outer list holds paths, inner lists hold tasks) is fine. You could make it slightly more explicit by using a set (unordered, suggesting equal alternatives) of tuples (ordered, suggesting a strict sequence), but that might be too subtle!
    – jonrsharpe
    Jul 30 '15 at 15:28
  • (it would also require your tasks to be hashable)
    – jonrsharpe
    Jul 30 '15 at 15:33
1

I find that naming intermediate results often provides semantic clarity to the humans reading it later, even if it doesn't change the end result. Like focusing a lens, sometimes the proper point is easiest to see by taking it to extremes then backing off. The extreme version of explicitness is:

def travel():
    yellow_cab_sequence = [call_yellow_cab, ride_yellow_cab, pay_driver]
    limousine_sequence  = [call_limousine,  ride_limousine,  pay_driver]
    alternatives = [yellow_cab_sequence, limousine_sequence]
    return alternatives

This makes it abundantly explicit you are returning alternative sequences, although I would probably back off from this point a little and merge the last two lines. It also makes it easy to see opportunities to create function calls to reduce duplication or better separate abstraction levels, perhaps yellow_cab_sequence() or even ground_transportation_sequence("yellow cab").

You could also add clarity by choosing a name for the function such as travel_alternatives.

On the other hand, if your code truly stays as simple as your example, it's clear enough as-is. Just keep the technique in mind as the complexity grows of explicitly naming intermediate results or splitting them into functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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