itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)
Bengt Richter
bokr at oz.net
Tue Mar 29 19:10:09 EST 2005
On Tue, 29 Mar 2005 11:32:33 -0800, Michael Spencer <mahs at telcopartners.com> 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:
That last "otherwise" is pretty important for strings as in int('1234') ;-)
>
>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
But wouldn't you really currently write the "->" form from above? I.e.,
for ordchar in (ord(c) for c in somestring):
...
to compare with
>to
>for ordchar in ord(somestring):
> ...
>
So it's not _that_ much shorter ;-)
>It would not work for summarizing functions or those that can accept an iterable
>today e.g., len, repr
>
I like concise expression, so I'm willing to try it. I guess it would be enough
to override __builtins__ to get a taste, e.g., (not thought through):
>>> class itint(int):
... oldint = __builtins__.int
... def __new__(cls, arg):
... try: return cls.oldint(arg)
... except (TypeError, ValueError):
... oi = cls.oldint
... return (oi(item) for item in arg)
...
>>> __builtins__.int = itint
>>> int('1234')
1234
>>> for x in int('1 23 456'.split()): print x,
...
1 23 456
>>> for x in int(range(1,8,2)): print x,
...
1 3 5 7
>>> for x in int('123x'): print x,
...
1 2 3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in <generator expression>
ValueError: invalid literal for int(): x
Hm, ... ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list