Python 3 coerce () equivalent

coerce()

a function that

returns a tuple of two numeric arguments converted to a common type using the same rules used by arithmetic operations

deprecated in Python 3. I would like to know if there are any equivalent functions introduced in Python 3.x?

+3


source to share


2 answers


Even if you don't need it anymore (and therefore you shouldn't use it either, unless you're working with legacy code), you can simply:



def coerce(x, y):
    t = type(x + y)
    return (t(x), t(y))

      

+3


source


The reason for the removal coerce()

in python 3 is that it is no longer up to date, see http://python3porting.com/differences.html#coerce-and-coerce

You are expected to be able to just use arithmetic operators without coercion, and you are expected to be explicit when formatting the output for display. This was the case with pep-3141 in 2007, which was already implemented in python 2.6, the oldest supported language version.



I would be tempted to be more combative than the accepted answer, saying that you really shouldn't try to do this. To rely on python versions that would break it would just hurt you in a different way.

+2


source







All Articles