[Python-ideas] __len__() for map()
E. Madison Bray
erik.m.bray at gmail.com
Thu Nov 29 05:32:20 EST 2018
On Wed, Nov 28, 2018 at 11:59 PM Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>
> E. Madison Bray wrote:
> > So I might want to check:
> >
> > finite_definite = True
> > for it in my_map.iters:
> > try:
> > len(it)
> > except TypeError:
> > finite_definite = False
> >
> > if finite_definite:
> > my_seq = list(my_map)
> > else:
> > # some other algorithm
>
> If map is being passed into your function, you can still do this
> check before calling map.
>
> If the user is doing the mapping themselves, then in Python 2 it
> would have blown up anyway before your function even got called,
> so nothing is any worse.
You either missed, or completely ignored, my previous message where I
addressed this:
"For example, previously a user might pass map(func, some_list) where
func is some pure function and the iterable is almost always a list of
some kind. Previously that map() call would be evaluated (often
slowly) first.
But now we can treat a map as something a little more formal, as a
container for a function and one or more iterables, which happens to
have this special functionality when you iterate over it, but is
otherwise just a special container. This is technically already the
case, we just can't directly access it as a container. If we could, it
would be possible to implement various optimizations that a user might
not have otherwise been obvious to the user. This is especially the
case of the iterable is a simple list, which is something we can
check. The function in this case very likely might actually be a C
function that was wrapped with Cython. I can easily convert this on
the user's behalf to a simple C loop or possibly even some other more
optimal vectorized code.
These are application-specific special cases of course, but many such
cases become easily accessible if map() and friends are usable as
specialized containers."
More information about the Python-ideas
mailing list