What are common uses for Python's built-in coerce
function? I can see applying it if I do not know the type
of a numeric value as per the documentation, but do other common usages exist? I would guess that coerce()
is also called when performing arithmetic computations, e.g. x = 1.0 +2
. It's a built-in function, so presumably it has some potential common usage?
Asked
Active
Viewed 2.2k times
25
-
7Never heard of `coerce()` (+1) – NPE Jan 23 '13 at 18:32
-
2Deprecated, not used on Python 2.6 or 3 – imreal Jan 23 '13 at 18:34
-
11If you read the note at the top of the section of the documentation you linked to, you shouldn't use it, nor should you need to know it exists. – Wooble Jan 23 '13 at 18:35
-
@Wooble coerce() was just far enough down that I missed the heading. What was the usage? – Jzl5325 Jan 23 '13 at 18:37
-
Note: **Python programmers, trainers, students and book writers should feel free to bypass these functions without concerns about missing something important.** – Ashwini Chaudhary Jan 23 '13 at 18:38
-
1I'm just trying to find a post I made on c.l.p on this, but no luck so far! LOL – Jon Clements Jan 23 '13 at 18:38
-
My guess is coerce() was implemented as a work-around for some problem. Now that we found a better, more elegant way to solve that problem, coerce() is becoming obsolete. – Hai Vu Jan 23 '13 at 18:41
-
11Just because you "don't need to know" something doesn't mean you shouldn't *want* to know it. – Russell Borogove Jan 23 '13 at 18:41
-
Some of the thread that may (or may not) be of use http://article.gmane.org/gmane.comp.python.general/494305/match=list+typeerror (wow - can't believe I wrote that 6 years ago!) – Jon Clements Jan 23 '13 at 18:42
-
1related : http://www.python.org/dev/peps/pep-0208/ – Ashwini Chaudhary Jan 23 '13 at 18:51
2 Answers
15
Its a left over from early python, it basically makes a tuple of numbers to be the same underlying number type e.g.
>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>
It is also to allow objects to act like numbers with old classes
(a bad example of its usage here would be ...)
>>> class bad:
... """ Dont do this, even if coerce was a good idea this simply
... makes itself int ignoring type of other ! """
... def __init__(self, s):
... self.s = s
... def __coerce__(self, other):
... return (other, int(self.s))
...
>>> coerce(10, bad("102"))
(102, 10)

Greg Bowyer
- 1,684
- 13
- 14
2
Python core programing says:
Function coerce () provides the programmer do not rely on the Python interpreter, but custom two numerical type conversion."
e.g.
>>> coerce(1, 2)
(1, 2)
>>>
>>> coerce(1.3, 134L)
(1.3, 134.0)
>>>
>>> coerce(1, 134L)
(1L, 134L)
>>>
>>> coerce(1j, 134L)
(1j, (134+0j))
>>>
>>> coerce(1.23-41j, 134L)
((1.23-41j), (134+0j))

Keale
- 3,924
- 3
- 29
- 46

dEMON_hUNTER
- 21
- 3