Python iteration anti-patterns
17 Mar 2010So I watched a slideshow where an author (name intentionally omitted) had a snippet that iterated over a list in python. It really bugged me that he checked for the length of the array first, and then iterated. This isn't really idiomatic and since calling len() on a None will raise an exception, the only sane choices are to check for null explicetly or wrap in a try/catch.
This just feels wrong and I wanted to make two styleistic points here.
1) IF you have a method that returns a list, always return a list. If it is empty don't return None and make me check if the value is None or not. Just return an empty list []
2) If code follows step #1, don't check - just iterate. If the list is empty obviously the iteration will never happen which is what is desired in the snippet above.