r/Python • u/RickSore • Nov 14 '17
Senior Python Programmers, what tricks do you want to impart to us young guns?
Like basic looping, performance improvement, etc.
1.3k
Upvotes
r/Python • u/RickSore • Nov 14 '17
Like basic looping, performance improvement, etc.
1
u/NoLemurs Nov 16 '17 edited Nov 16 '17
This doesn't help at all. An empty iterator is still truthy. In fact, this makes things worse:
It's hard to keep track of the intricacies of all these different approaches. But the behavior of the
if myCollectioncheck, when applied to things that aren't actually lists, tuples, or dictionaries, requires you to be thinking about these things and to know the behavior backwards and forwards. To me that makes the code much less readable.Duck typing is good as long as the thing you're duck typing on is logically the thing you care about. Once you start duck-typing on something that's just a proxy for the thing you care about you start moving into territory where your code may look nice, but it has a bunch of hidden gotcha's that you have to be aware of - all the cases where the thing you're duck-typing on isn't actually the thing you care about. The result is bug prone, and despite looking simple, much more complex and difficult to understand than a more explicit version.
EDIT: I'll add that the reason I knew how
iterwould behave is that iterators don't have a concept of length - they can't because they have to handle potentially infinite items. Since python doesn't really have a distinct idea of a collection being 'empty', a collection (like an iterator) with no length is always going to be truthy because there's no relevant specific idea of truthiness, andObjectis truthy by default. This is why theif len(myCollection) > 0check makes sense. It is checking the condition that is most closely tied to the idea of 'non-emptiness'. If python collections had anis_empty()method - that would be the thing to check.