By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,775 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

automatically mapping builtins (WAS: itertools to iter transition)

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Steven Bethard wrote:
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:
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 Richter wrote: 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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.