automatically mapping builtins (WAS: itertools to iter transition)

S

Steven Bethard

Michael said:
> While we're on the topic, what do you think of having unary,
> non-summary builtins automatically map themselves when called with an
> iterable that would otherwise be an illegal argument:
>
> e.g.,
> int(iterable) -> (int(i) for i in iterable)
> ord(iterable) -> (ord(i) for i in iterable)
>
>
> This would be unambiguous, I think, in the cases of bool, int,
> callable, chr, float, hex, id, long, oct, ord, vars...
>
> It would shorten the common cases of:
> for char in somestring:
> ordchar = ord(char)
> # do something with ordchar, but not char
> to
> for ordchar in ord(somestring):
> ...
>
> It would not work for summarizing functions or those that can accept
> an iterable today e.g., len, repr

I personally don't much like the idea because I expect 'int' to produce
an int, just like I expect 'list' to produce a list. So having 'int'
produce an iterable in any situation seems inappropriate to me.

Also, you probably can't do this for bool:

py> i = iter(range(2))
py> bool(i)
True
py> list(i)
[0, 1]
py> bool(i)
False

If an iterator object has a __len__ method, bool will use it. Similarly
for int, float, etc.:

py> class I(object):
.... def __iter__(self):
.... return self
.... def next(self):
.... return 1
.... def __int__(self):
.... return 1
.... def __float__(self):
.... return 1.0
....
py> i = iter(I())
py> int(i)
1
py> float(i)
1.0

STeVe
 
M

Michael Spencer

Steven said:
Michael said:
While we're on the topic, what do you think of having unary,
non-summary builtins automatically map themselves when called with an
iterable that would otherwise be an illegal argument:

I personally don't much like the idea because I expect 'int' to produce
an int, just like I expect 'list' to produce a list. So having 'int'
produce an iterable in any situation seems inappropriate to me.

[...]
Bengt said:
That last "otherwise" is pretty important for strings as in int('1234') ;-)
[snip]

But wouldn't you really currently write the "->" form from above? I.e.,

for ordchar in (ord(c) for c in somestring):
...

Thanks for the reactions, (and test implementation, Bengt)

Something to play with, but the idea doesn't seem like a big win, when the
explicit genexp is fully general and only slightly more verbose.


Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top