Implement isinstance(x, (A, B, ...)). Note that we only allow tuples, · python/cpython@03290ec (original) (raw)
2 files changed
lines changed
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1805,6 +1805,20 @@ PyObject_IsInstance(PyObject *inst, PyObject *cls) | ||
1805 | 1805 | else if (PyType_Check(cls)) { |
1806 | 1806 | retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); |
1807 | 1807 | } |
1808 | +else if (PyTuple_Check(cls)) { | |
1809 | +/* Not a general sequence -- that opens up the road to | |
1810 | + recursion and stack overflow. */ | |
1811 | +int i, n; | |
1812 | + | |
1813 | +n = PyTuple_GET_SIZE(cls); | |
1814 | +for (i = 0; i < n; i++) { | |
1815 | +retval = PyObject_IsInstance( | |
1816 | +inst, PyTuple_GET_ITEM(cls, i)); | |
1817 | +if (retval != 0) | |
1818 | +break; | |
1819 | + } | |
1820 | +return retval; | |
1821 | + } | |
1808 | 1822 | else if (!PyInstance_Check(inst)) { |
1809 | 1823 | if (__class__ == NULL) { |
1810 | 1824 | __class__ = PyString_FromString("__class__"); |
@@ -1827,7 +1841,8 @@ PyObject_IsInstance(PyObject *inst, PyObject *cls) | ||
1827 | 1841 | |
1828 | 1842 | if (retval < 0) { |
1829 | 1843 | PyErr_SetString(PyExc_TypeError, |
1830 | -"isinstance() arg 2 must be a class or type"); | |
1844 | +"isinstance() arg 2 must be a class or type " | |
1845 | +"or tuple of those"); | |
1831 | 1846 | } |
1832 | 1847 | return retval; |
1833 | 1848 | } |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1641,10 +1641,12 @@ builtin_isinstance(PyObject *self, PyObject *args) | ||
1641 | 1641 | } |
1642 | 1642 | |
1643 | 1643 | static char isinstance_doc[] = |
1644 | -"isinstance(object, class-or-type) -> Boolean\n\ | |
1644 | +"isinstance(object, class-or-type-or-tuple) -> Boolean\n\ | |
1645 | 1645 | \n\ |
1646 | 1646 | Return whether an object is an instance of a class or of a subclass thereof.\n\ |
1647 | -With a type as second argument, return whether that is the object's type."; | |
1647 | +With a type as second argument, return whether that is the object's type.\n\ | |
1648 | +The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\ | |
1649 | +isinstance(x, A) or isinstance(x, B) or ... (etc.)."; | |
1648 | 1650 | |
1649 | 1651 | |
1650 | 1652 | static PyObject * |