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/b1ackcat Nov 15 '17 edited Nov 15 '17
Well I have to disagree.
Being more "pythonic" just for the sake of it is idiotic. That point alone just sounds so pretentious I almost stopped reading. Code needs to be readable, extendable, and maintainable. None of those requirements insist upon blindly following some language-specific dogma.
The two conditions actually behave differently. Checking the length explicitly will raise an exception for a None object, whereas checking just the object will return false. More often than not, the former behavior is more desirable, since code should generally fail fast.
Checking __len__ is not usually O(n). It depends on the implementation of the collection, and most if not all of the standard Python collection classes track the size in an attribute, so it's usually O(1). I'll grant you that this isn't the most obvious behavior, but still, an important distinction.
If the object isn't expected to always be a collection (like a float or something), you already have at best, unmaintainable code, and at worst, a bug, if the condition is relying on the assumption that the object is a collection. Again, checking length here catches that issue, checking the object directly doesn't.
Read the PEP for this condition check. Even the author admits this lint check is probably not the best idea/needs to be rethought. It's just not a good warning, at all.