<p dir="ltr"><br>
On Apr 19, 2014 2:54 PM, "Chris Angelico" <<a href="mailto:rosuav@gmail.com">rosuav@gmail.com</a>> wrote:<br>
><br>
> On Sun, Apr 20, 2014 at 6:38 AM, Ian Kelly <<a href="mailto:ian.g.kelly@gmail.com">ian.g.kelly@gmail.com</a>> wrote:<br>
> >> Or you just cast one of them to float. That way you're sure you're<br>
> >> working with floats.<br>
> ><br>
> > Which is inappropriate if the type passed in was a Decimal or a complex.<br>
><br>
> In that case, you already have a special case in your code, so whether<br>
> that special case is handled by the language or by your code makes<br>
> little difference. Is your function so generic that it has to be able<br>
> to handle float, Decimal, or complex, and not care about the<br>
> difference, and yet has to ensure that int divided by int doesn't<br>
> yield int? Then say so; put in that special check. Personally, I've<br>
> yet to meet any non-toy example of a function that needs that exact<br>
> handling; most code doesn't ever think about complex numbers, and a<br>
> lot of things look for one specific type:</p>
<p dir="ltr">When I'm writing a generic average function, I probably don't know whether it will ever be used to average complex numbers. That shouldn't matter, because I should be able to rely on this code working for whatever numeric type I pass in:</p>

<p dir="ltr">def average(values):<br>
    return sum(values) / len(values)</p>
<p dir="ltr">This works for decimals, it works for fractions, it works for complex numbers, it works for numpy types, and in Python 3 it works for ints.</p>
<p dir="ltr">> Maybe it's not your code that should be caring about what happens when<br>
> you divide two integers, but the calling code. If you're asking for<br>
> the average of a list of numbers, and they're all integers, and the<br>
> avg() function truncates to integer, then the solution is to use sum()<br>
> and explicitly cast to floating point before dividing.</p>
<p dir="ltr">First, that's not equivalent.  Try the following in Python 3:</p>
<p dir="ltr">values = [int(sys.float_info.max / 10)] * 20<br>
print(average(values))</p>
<p dir="ltr">Now try this:</p>
<p dir="ltr">print(average(map(float, values)))</p>
<p dir="ltr">I don't have an interpreter handy to test, but I expect the former to produce the correct result and the latter to raise OverflowError on the call to sum.</p>
<p dir="ltr">Second, why should the calling code have to worry about this implementation detail anyway? The point of a generic function is that it's generic.</p>