| 3783 | |
| 3784 | @pytest.mark.numpy |
| 3785 | def test_numpy_array_protocol(): |
| 3786 | # test the __array__ method on pyarrow.Array |
| 3787 | arr = pa.array([1, 2, 3]) |
| 3788 | result = np.asarray(arr) |
| 3789 | expected = np.array([1, 2, 3], dtype="int64") |
| 3790 | np.testing.assert_array_equal(result, expected) |
| 3791 | |
| 3792 | # this should not raise a deprecation warning with numpy 2.0+ |
| 3793 | result = np.array(arr, copy=False) |
| 3794 | np.testing.assert_array_equal(result, expected) |
| 3795 | |
| 3796 | result = np.array(arr, dtype="int64", copy=False) |
| 3797 | np.testing.assert_array_equal(result, expected) |
| 3798 | |
| 3799 | # no zero-copy is possible |
| 3800 | arr = pa.array([1, 2, None]) |
| 3801 | expected = np.array([1, 2, np.nan], dtype="float64") |
| 3802 | result = np.asarray(arr) |
| 3803 | np.testing.assert_array_equal(result, expected) |
| 3804 | |
| 3805 | if Version(np.__version__) < Version("2.0.0.dev0"): |
| 3806 | # copy keyword is not strict and not passed down to __array__ |
| 3807 | result = np.array(arr, copy=False) |
| 3808 | np.testing.assert_array_equal(result, expected) |
| 3809 | |
| 3810 | result = np.array(arr, dtype="float64", copy=False) |
| 3811 | np.testing.assert_array_equal(result, expected) |
| 3812 | else: |
| 3813 | # starting with numpy 2.0, the copy=False keyword is assumed to be strict |
| 3814 | with pytest.raises(ValueError, match="Unable to avoid a copy"): |
| 3815 | np.array(arr, copy=False) |
| 3816 | |
| 3817 | arr = pa.array([1, 2, 3]) |
| 3818 | with pytest.raises(ValueError): |
| 3819 | np.array(arr, dtype="float64", copy=False) |
| 3820 | |
| 3821 | # copy=True -> not yet passed by numpy, so we have to call this directly to test |
| 3822 | arr = pa.array([1, 2, 3]) |
| 3823 | result = arr.__array__(copy=True) |
| 3824 | assert result.flags.writeable |
| 3825 | |
| 3826 | arr = pa.array([1, 2, 3]) |
| 3827 | result = arr.__array__(dtype=np.dtype("float64"), copy=True) |
| 3828 | assert result.dtype == "float64" |
| 3829 | |
| 3830 | |
| 3831 | @pytest.mark.numpy |