Skip to content

Commit 537a9ad

Browse files
authored
Do not raise error when decimal.Decimal import fails (#219)
[skip ci]
1 parent 25a6668 commit 537a9ad

File tree

3 files changed

+6
-20
lines changed

3 files changed

+6
-20
lines changed

src/pysorteddict/sorted_dict_module.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,5 +826,6 @@ PyMODINIT_FUNC PyInit_pysorteddict(void)
826826
Py_DECREF(mod);
827827
return nullptr;
828828
}
829+
import_supported_key_types();
829830
return mod;
830831
}

src/pysorteddict/sorted_dict_type.cc

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -50,22 +50,10 @@ static PyTypeObject* PyDecimal_Type;
5050
/**
5151
* Import all supported key types from Python which are not built-in. Make them
5252
* available globally so that their reference counts need not be managed.
53-
*
54-
* @return `true` if successful, else `false`.
5553
*/
56-
static bool import_supported_key_types(void)
54+
void import_supported_key_types(void)
5755
{
58-
// Import each type only once.
59-
static bool import_decimal = []
60-
{
61-
return (PyDecimal_Type = import_python_type("decimal", "Decimal")) != nullptr;
62-
}();
63-
if (!import_decimal)
64-
{
65-
PyErr_SetString(PyExc_ImportError, "failed to import the `decimal.Decimal` type");
66-
return false;
67-
}
68-
return true;
56+
PyDecimal_Type = import_python_type("decimal", "Decimal");
6957
}
7058

7159
/**
@@ -139,7 +127,7 @@ bool SortedDictType::are_key_type_and_key_value_pair_good(PyObject* key, PyObjec
139127
};
140128
for (PyTypeObject* allowed_key_type : allowed_key_types)
141129
{
142-
if (Py_IS_TYPE(key, allowed_key_type) != 0)
130+
if (allowed_key_type != nullptr && Py_IS_TYPE(key, allowed_key_type) != 0)
143131
{
144132
this->key_type = allowed_key_type;
145133
key_type_set_here = true;
@@ -523,11 +511,6 @@ int SortedDictType::init(PyObject* args, PyObject* kwargs)
523511

524512
PyObject* SortedDictType::New(PyTypeObject* type, PyObject* args, PyObject* kwargs)
525513
{
526-
if (!import_supported_key_types())
527-
{
528-
return nullptr;
529-
}
530-
531514
PyObject* self = type->tp_alloc(type, 0); // 🆕
532515
if (self == nullptr)
533516
{

src/pysorteddict/sorted_dict_type.hh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
#include <Python.h>
66
#include <map>
77

8+
void import_supported_key_types(void);
9+
810
/**
911
* C++-style comparison implementation for Python objects.
1012
*/

0 commit comments

Comments
 (0)