coerce() equivalent in python 3

后端 未结 2 474
闹比i
闹比i 2021-01-06 13:26

coerce() function which

returns a tuple consisting of the two numeric arguments converted to a common type, using the same rules as us

相关标签:
2条回答
  • 2021-01-06 14:12

    The reason for coerce() being removed in python 3 is that it is no longer relevant, please see http://python3porting.com/differences.html#coerce-and-coerce

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

    I would be tempted to be more militant than the accepted answer in saying that you really shouldn't be trying to do this. To rely on python versions that this would break, will simple hurt you in many other ways.

    0 讨论(0)
  • 2021-01-06 14:19

    Even if it's no longer needed (and thus you also should not use this if you're not working on legacy code) you can just do:

    def coerce(x, y):
        t = type(x + y)
        return (t(x), t(y))
    
    0 讨论(0)
提交回复
热议问题