| 3666 | |
| 3667 | @pytest.mark.numpy |
| 3668 | def test_numpy_array_protocol(): |
| 3669 | # test the __array__ method on pyarrow.Array |
| 3670 | arr = pa.array([1, 2, 3]) |
| 3671 | result = np.asarray(arr) |
| 3672 | expected = np.array([1, 2, 3], dtype="int64") |
| 3673 | np.testing.assert_array_equal(result, expected) |
| 3674 | |
| 3675 | # this should not raise a deprecation warning with numpy 2.0+ |
| 3676 | result = np.array(arr, copy=False) |
| 3677 | np.testing.assert_array_equal(result, expected) |
| 3678 | |
| 3679 | result = np.array(arr, dtype="int64", copy=False) |
| 3680 | np.testing.assert_array_equal(result, expected) |
| 3681 | |
| 3682 | # no zero-copy is possible |
| 3683 | arr = pa.array([1, 2, None]) |
| 3684 | expected = np.array([1, 2, np.nan], dtype="float64") |
| 3685 | result = np.asarray(arr) |
| 3686 | np.testing.assert_array_equal(result, expected) |
| 3687 | |
| 3688 | if Version(np.__version__) < Version("2.0.0.dev0"): |
| 3689 | # copy keyword is not strict and not passed down to __array__ |
| 3690 | result = np.array(arr, copy=False) |
| 3691 | np.testing.assert_array_equal(result, expected) |
| 3692 | |
| 3693 | result = np.array(arr, dtype="float64", copy=False) |
| 3694 | np.testing.assert_array_equal(result, expected) |
| 3695 | else: |
| 3696 | # starting with numpy 2.0, the copy=False keyword is assumed to be strict |
| 3697 | with pytest.raises(ValueError, match="Unable to avoid a copy"): |
| 3698 | np.array(arr, copy=False) |
| 3699 | |
| 3700 | arr = pa.array([1, 2, 3]) |
| 3701 | with pytest.raises(ValueError): |
| 3702 | np.array(arr, dtype="float64", copy=False) |
| 3703 | |
| 3704 | # copy=True -> not yet passed by numpy, so we have to call this directly to test |
| 3705 | arr = pa.array([1, 2, 3]) |
| 3706 | result = arr.__array__(copy=True) |
| 3707 | assert result.flags.writeable |
| 3708 | |
| 3709 | arr = pa.array([1, 2, 3]) |
| 3710 | result = arr.__array__(dtype=np.dtype("float64"), copy=True) |
| 3711 | assert result.dtype == "float64" |
| 3712 | |
| 3713 | |
| 3714 | @pytest.mark.numpy |