Private function validating the given `fill_value` for the given dtype. If fill_value is None, it is set to the default corresponding to the dtype. If fill_value is not None, its value is forced to the given dtype. The result is always a 0d array.
(fill_value, ndtype)
| 465 | |
| 466 | |
| 467 | def _check_fill_value(fill_value, ndtype): |
| 468 | """ |
| 469 | Private function validating the given `fill_value` for the given dtype. |
| 470 | |
| 471 | If fill_value is None, it is set to the default corresponding to the dtype. |
| 472 | |
| 473 | If fill_value is not None, its value is forced to the given dtype. |
| 474 | |
| 475 | The result is always a 0d array. |
| 476 | |
| 477 | """ |
| 478 | ndtype = np.dtype(ndtype) |
| 479 | if fill_value is None: |
| 480 | fill_value = default_fill_value(ndtype) |
| 481 | # TODO: It seems better to always store a valid fill_value, the oddity |
| 482 | # about is that `_fill_value = None` would behave even more |
| 483 | # different then. |
| 484 | # (e.g. this allows arr_uint8.astype(int64) to have the default |
| 485 | # fill value again...) |
| 486 | # The one thing that changed in 2.0/2.1 around cast safety is that the |
| 487 | # default `int(99...)` is not a same-kind cast anymore, so if we |
| 488 | # have a uint, use the default uint. |
| 489 | if ndtype.kind == "u": |
| 490 | fill_value = np.uint(fill_value) |
| 491 | elif ndtype.names is not None: |
| 492 | if isinstance(fill_value, (ndarray, np.void)): |
| 493 | try: |
| 494 | fill_value = np.asarray(fill_value, dtype=ndtype) |
| 495 | except ValueError as e: |
| 496 | err_msg = "Unable to transform %s to dtype %s" |
| 497 | raise ValueError(err_msg % (fill_value, ndtype)) from e |
| 498 | else: |
| 499 | fill_value = np.asarray(fill_value, dtype=object) |
| 500 | fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype), |
| 501 | dtype=ndtype) |
| 502 | elif isinstance(fill_value, str) and (ndtype.char not in 'OSTVU'): |
| 503 | # Note this check doesn't work if fill_value is not a scalar |
| 504 | err_msg = "Cannot set fill value of string with array of dtype %s" |
| 505 | raise TypeError(err_msg % ndtype) |
| 506 | else: |
| 507 | # In case we want to convert 1e20 to int. |
| 508 | # Also in case of converting string arrays. |
| 509 | try: |
| 510 | fill_value = np.asarray(fill_value, dtype=ndtype) |
| 511 | except (OverflowError, ValueError) as e: |
| 512 | # Raise TypeError instead of OverflowError or ValueError. |
| 513 | # OverflowError is seldom used, and the real problem here is |
| 514 | # that the passed fill_value is not compatible with the ndtype. |
| 515 | err_msg = "Cannot convert fill_value %s to dtype %s" |
| 516 | raise TypeError(err_msg % (fill_value, ndtype)) from e |
| 517 | return np.array(fill_value) |
| 518 | |
| 519 | |
| 520 | def set_fill_value(a, fill_value): |
searching dependent graphs…