Skip to content

bpo-33083 - math.factorial accepts non-integral Decimal instances #6149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/test/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from test import support
import unittest
import itertools
import decimal
import math
import os
import platform
Expand Down Expand Up @@ -510,6 +511,10 @@ def testFactorial(self):
self.assertRaises(ValueError, math.factorial, -1e100)
self.assertRaises(ValueError, math.factorial, math.pi)

def testFactorialNonIntegers(self):
self.assertRaises(TypeError, math.factorial, decimal.Decimal(5.2))
self.assertRaises(TypeError, math.factorial, "5")

# Other implementations may place different upper bounds.
@support.cpython_only
def testFactorialHugeInputs(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
``math.factorial`` no longer accepts arguments that are not int-like.
Patch by Pablo Galindo.
12 changes: 9 additions & 3 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1656,7 +1656,7 @@ math_factorial(PyObject *module, PyObject *arg)
{
long x;
int overflow;
PyObject *result, *odd_part, *two_valuation;
PyObject *result, *odd_part, *two_valuation, *pyint_form;

if (PyFloat_Check(arg)) {
PyObject *lx;
Expand All @@ -1672,8 +1672,14 @@ math_factorial(PyObject *module, PyObject *arg)
x = PyLong_AsLongAndOverflow(lx, &overflow);
Py_DECREF(lx);
}
else
x = PyLong_AsLongAndOverflow(arg, &overflow);
else {
pyint_form = PyNumber_Index(arg);
if (pyint_form == NULL) {
return NULL;
}
x = PyLong_AsLongAndOverflow(pyint_form, &overflow);
Py_DECREF(pyint_form);
}

if (x == -1 && PyErr_Occurred()) {
return NULL;
Expand Down