automatically mapping builtins (WAS: itertools to iter transition)

Steven Bethard steven.bethard at gmail.com
Tue Mar 29 17:07:04 EST 2005


Michael Spencer wrote:
 > 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



More information about the Python-list mailing list