6 ms·
To be fair, using "if something" in Python is pretty much always a good way to trip yourself up.
by fantod 6y ago
To be fair, using "if something" in Python is pretty much always a good way to trip yourself up.
- pansa2 6y agoPEP8 recommends using `if seq:` instead of more verbose alternatives like `if len(seq):`.
- orf 6y agoFor good reason - len(something) or alternatives might be expensive to compute, bool(something) is actually what you are trying to do and can be optimised depending on the container.
- fantod 6y agoFor the basic sequence types (list, tuple, and range), len is definitely not expensive to compute. For custom types, it will depend on your implementation of __len__ (but then, computation of bool(...) will also depend on your implementation of __bool__).
- orf 6y agoYes, len() with the basic types are not expensive, and it can vary based on the container implementation, but that’s not really the point. The reason you should use “if x” is the same reason you should use “if x not in y” rather than “if not x in y”. It better expresses the semantics of your operation with the side effect that it may be faster.
- fantod 6y agoOh yeah, totally agree that it's idiomatic and (in my opinion) cleaner.
- fantod 6y agoIf you know that "something" is a sequence, then is the idiomatic thing to do. The point is that any time you rely on truthiness of a value, you need to think (sometimes quite carefully) about what type of value you're dealing with.
- nemetroid 6y agoI've yet to see a (popular) style guide recommend against "if something:".
- fantod 6y agoI don't really see how this is a reason not to carefully consider the type of an object when using truthiness.