Converts a Python object to a bfloat16 value. Returns true on success, returns false and reports a Python error on failure.
| 106 | // Converts a Python object to a bfloat16 value. Returns true on success, |
| 107 | // returns false and reports a Python error on failure. |
| 108 | bool AsBfloat16(PyObject* arg, bfloat16* output) { |
| 109 | if (PyBfloat16_Check(arg)) { |
| 110 | *output = PyBfloat16_Bfloat16(arg); |
| 111 | return true; |
| 112 | } |
| 113 | if (PyFloat_Check(arg)) { |
| 114 | double d = PyFloat_AsDouble(arg); |
| 115 | if (PyErr_Occurred()) { |
| 116 | return false; |
| 117 | } |
| 118 | // TODO(phawkins): check for overflow |
| 119 | *output = bfloat16(d); |
| 120 | return true; |
| 121 | } |
| 122 | if (TfPyInt_Check(arg)) { |
| 123 | long l = TfPyInt_AsLong(arg); // NOLINT |
| 124 | if (PyErr_Occurred()) { |
| 125 | return false; |
| 126 | } |
| 127 | // TODO(phawkins): check for overflow |
| 128 | *output = bfloat16(static_cast<float>(l)); |
| 129 | return true; |
| 130 | } |
| 131 | if (PyArray_IsScalar(arg, Float)) { |
| 132 | float f; |
| 133 | PyArray_ScalarAsCtype(arg, &f); |
| 134 | *output = bfloat16(f); |
| 135 | return true; |
| 136 | } |
| 137 | PyErr_Format(PyExc_TypeError, "expected number, got %s", |
| 138 | arg->ob_type->tp_name); |
| 139 | return false; |
| 140 | } |
| 141 | |
| 142 | // Converts a PyBfloat16 into a PyFloat. |
| 143 | PyObject* PyBfloat16_Float(PyObject* self) { |
no test coverage detected