On Fri, Oct 30, 2020 at 1:06 PM Julio Di Egidio <ju...@diegidio.name> wrote: > > On Sunday, 25 October 2020 20:55:26 UTC+1, Peter J. Holzer wrote: > > I think you are trying to use Python in a way contrary to its nature. > > Python is a dynamically typed language. Its variables don't have types, > > only its objects. And basically everything can be changed at runtime ... > > Consider this example: > > def abs(x): > return math.sqrt(x.re**2 + x.im**2) > > That of course fails if we pass an object not of the correct > (duck) type. But the exception is raised by math.sqrt, which, > properly speaking, beside considerations on usability, is a > private detail of the implementation of abs.
Not sure what sorts of errors you're expecting, but for the most part, if it's not a complex number, you should get an AttributeError before you get into the sqrt. (Although I'm not sure why you're looking for ".re" and ".im" - typo? Python's complex type has ".real" and ".imag", and you can accept any numeric type that way - even fractions.Fraction.) It's highly unlikely that you'd have real and imaginary parts that can be squared and summed, but the result can't be squirted. But here's the thing: even if that IS the case, most Python programmers are fine with getting an AttributeError stating exactly what the problem is, rather than a TypeError complaining that it has to be the exact type some other programmer intended. A good example is dictionaries and dict-like objects; if your code type checks for a dict, I have to give you a dict, but if you just try to do whichever operations you need, I can create something more dynamic and give you that instead. Python doesn't push for heavy type checking because it's almost certainly not necessary in the majority of cases. Just use the thing as you expect it to be, and if there's a problem, your caller can handle it. That's why we have call stacks. ChrisA -- https://mail.python.org/mailman/listinfo/python-list