4 ms·
len(my_list) is just sugar for my_list.__len__() if you feel strongly about the convention: https://docs.python.org/3/reference/datamodel.html#object.__l
by dfinninger 5y ago
len(my_list)
is just sugar for
my_list.__len__()
if you feel strongly about the convention: https://docs.python.org/3/reference/datamodel.html#object.__len__ https://docs.python.org/3/reference/datamodel.html#object.__...
- int_19h 5y agoIt's not just sugar; it also does things like ensuring that the value is actually a nonnegative integer. And for other unary "magic methods", the disconnect can be even bigger. E.g. iter(x) is not just a synonym for x.__iter__() - it can also produce an iterator for something that only provides __len__ and __getitem__.
- dragonwriter 5y agoThis is, I think, largely a result of Python not idiomatically using mixins as much as Ruby (since it has multiple inheritance, it supports them, and they are sometimes used, but Ruby leans into them hard in the core.) In the Ruby way, with otherwise similar setup, you would have a mixin that provided __iter__() given __len__() and __getitem__(), and classes that had the last two but wanted the behavior of the first would just include that mixin class as a parent, rather than having a separate branch in iter() to handle the different cases. (Ironically, its one way that Ruby is less TMTOWTDI than Python is.)
- progval 5y ago> In the Ruby way, with otherwise similar setup, you would have a mixin that provided __iter__() given __len__() and __getitem__(), Python does have such a mixing, it's collections.abc.Sequence https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes https://docs.python.org/3/library/collections.abc.html#colle...