[Python-ideas] [Python-Dev] minmax() function returning (minimum, maximum) tuple of a sequence
Ron Adam
rrr at ronadam.com
Fri Oct 15 20:09:17 CEST 2010
On 10/15/2010 12:27 PM, Georg Brandl wrote:
> Am 15.10.2010 19:13, schrieb Ron Adam:
>
>> [Tal also says]
>>> As Guido mentioned, there is never a reason to do max(value) where
>>> value is not an iterable.
>>
>> Well, you can always avoid doing it, but that doesn't mean it wouldn't be
>> nice to have sometimes. Take a look at the following three coroutines that
>> do the same exact thing. Which is easier to read and which would be
>> considered the more Pythonic.
>>
>>
>> def xmin(*args, **kwds):
>> # Allow min to work with a single non-iterable value.
>> if len(args) == 1 and not hasattr(args[0], "__iter__"):
>> return min(args, **kwds)
>> else:
>> return min(*args, **kwds)
>
> I don't understand this function. Why wouldn't you simply always call
>
> return min(args, **kwds)
>
> ?
Because it would always interpret a list of values as a single item.
This function looks at args and if its a single value without an "__iter__"
method, it passes it to min as min([value], **kwds) instead of min(value,
**kwds).
Another way to do this would be to use a try-except...
try:
return min(*args, **kwds)
except TypeError:
return min(args, **kwds)
Ron
More information about the Python-ideas
mailing list