3 ms·
I don't see how using len() this way is any different than doing an isinstance check. You're essentially saying, "If this object doesn't respond to len(), raise
by saila 5y ago
I don't see how using len() this way is any different than doing an isinstance check. You're essentially saying, "If this object doesn't respond to len(), raise a TypeError."
- mturmon 5y agoTuple, list, and numpy array are all different isinstance()’s, so I’d have to call them all out. len() avoids that.
- saila 5y agoThis is incorrect, because you can generally do this for sequence types: isinstance(items, Sequence) Or perhaps: isinstance(items, Iterable) # works with numpy arrays Or, equivalent to using len() for type checking, you could do: isinstance(items, Sized)
- dragonwriter 5y ago> I don't see how using len() this way is any different than doing an isinstance check. It's a protocol (structural) runtime type check, not a class (nominal) runtime type check.
- saila 5y agoPerhaps true but misses the point. If you’re using len() for type checking, it’s essentially no different than doing isinstance(items, Sized). The latter explicitly calls out what you’re doing and makes it clear, to me, that’s it’s not really correct, in that it doesn’t show your intent, which is to enforce a sequence of items in a container not that the object has a size.