Repository: numpy/numpy
Pull request: DOC: add examples to ctypeslib
- Add examples for ctypeslib: as_array, as_ctypes
- Partially closes #21351 

<!--         ----------------------------------------------------------------
                MAKE SURE YOUR PR GETS THE ATTENTION IT DESERVES!
                ----------------------------------------------------------------

*  FORMAT IT RIGHT:
      https://www.numpy.org/devdocs/dev/development_workflow.html#writing-the-commit-message

*  IF IT'S A NEW FEATURE OR API CHANGE, TEST THE WATERS:
      https://www.numpy.org/devdocs/dev/development_workflow.html#get-the-mailing-list-s-opinion

*  HIT ALL THE GUIDELINES:
      https://numpy.org/devdocs/dev/index.html#guidelines

*  WHAT TO DO IF WE HAVEN'T GOTTEN BACK TO YOU:
      https://www.numpy.org/devdocs/dev/development_workflow.html#getting-your-pr-reviewed
-->


Problem statement:
DOC: Examples in docstrings – tracking issue
"Examples, more examples, and more detailed examples" is the recurrent theme in the feedback about the NumPy documentation we received via the 2020 and 2021 NumPy user surveys. 

If you come across a docstring where a function is missing an example or more/better examples are needed, please add a comment below.

**Re: the “sprintable” label** This could be a good activity for a sprint with new contributors as most of them are NumPy users. However, one doesn’t have to be a sprint participant to contribute to this initiative.

Hints from issue discussion:
how can I help in this issue ?
Take a look at the functions you use from NumPy, and see if the docstrings have examples similar to your non-trivial use cases. If not, comment below asking if it seems an example would help newer users figure out how to replicate what you do.
This could be a good activity for a sprint with new contributors as most of them are NumPy users. I’ll add the “sprint” label to the issue. However, one doesn’t have to be a sprint participant to contribute to this initiative.
Hi everyone! 

One thing that could also be tracked is whether the existing examples in docstrings are following the standards listed in the documentation. I've found an example in `fromnumeric.py` (lines 171-189) that I'm not entirely sure that are in accordance to the documentation.

I'm willing to help on that.
Hi, Just wanted to confirm. If the general DOCS (examples for various functions) are in the scope of this Issue or we are currently tracking only the DOC Strings. 
I do see a lot of additions that can be done to the `numpy.random.generated` page
[Link under discussion](https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.integers.html)
I was talking to @InessaPawson about that. I do believe that this issue could be, in fact, split into several different ones. Even the docstrings, this could be split in tracking down the ones that are there, the ones that are not, the ones that follow the standards, et cetera.
We can use some examples in polynomial.py. What do you think about the following two (one for polymulx, the other for polyval2d):

```python
import numpy as np
from numpy.polynomial import polynomial as P

c=(-2, 0, 1)
P.polymulx(c)
#array([-0., -2.,  0.,  1.])


from numpy.polynomial.polynomial import polyval2d
a=polyval2d(2, -3j,  [(-1j,1.5,2), (1,0.2j,0)])  #This is -1jx⁰y⁰ + 1.5x⁰y¹ + 2x⁰y² + 1x¹y⁰ + 0.2jx¹y¹ + 0x¹y², evaluated at x = 2 and y=-3j
#(-14.799999999999997-5.5j)
```
> Just wanted to confirm. If the general DOCS (examples for various functions) are in the scope of this Issue or we are currently tracking only the DOC Strings.

@bhavukkalra This issue is only for examples in docstrings. Please file a separate issue for examples in other parts of the NumPy documentation.
@dbrs01 this looks good - Would you like to submit a PR? 
Thank you Melisssa. I appreciate your feedback.  I will do it (later) and
will continue including more examples. I have not been able to attend
meetings recently because I started a new job this past Monday and am in
the process of doing paperwork, installing my machine, going to the office
(no telework) and trying to get the most from my coworker from whom I
inherit tasks and whose last day of work is on May 30.  I hope to be back
soon. See you!

On Sat, May 14, 2022 at 7:13 AM Melissa Weber Mendonça <
***@***.***> wrote:

> @dbrs01 <https://github.com/dbrs01> this looks good - Would you like to
> submit a PR?
>
> —
> Reply to this email directly, view it on GitHub
> <https://github.com/numpy/numpy/issues/21351#issuecomment-1126714170>, or
> unsubscribe
> <https://github.com/notifications/unsubscribe-auth/ABXBEHY2CZLX6V47USVDDZLVJ6RJJANCNFSM5TTIU3GA>
> .
> You are receiving this because you were mentioned.Message ID:
> ***@***.***>
>


-- 
Dilia B. Rueda S.

Commit message: DOC: examples [skip azp] [skip actions] [skip cirrus]

add examples to ctyleslib: as_ctypes, as_array

Patch to review:
diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py
index 370cdf224cdc..821dcad37ca5 100644
--- a/numpy/ctypeslib.py
+++ b/numpy/ctypeslib.py
@@ -527,6 +527,26 @@ def as_array(obj, shape=None):
 
         The shape parameter must be given if converting from a ctypes POINTER.
         The shape parameter is ignored if converting from a ctypes array
+
+        Examples
+        --------
+        Converting a ctypes integer array:
+
+        >>> import ctypes
+        >>> ctypes_array = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
+        >>> np_array = np.ctypeslib.as_array(ctypes_array)
+        >>> np_array
+        array([0, 1, 2, 3, 4], dtype=int32)
+
+        Converting a ctypes POINTER:
+
+        >>> import ctypes
+        >>> buffer = (ctypes.c_int * 5)(0, 1, 2, 3, 4)
+        >>> pointer = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_int))
+        >>> np_array = np.ctypeslib.as_array(pointer, (5,))
+        >>> np_array
+        array([0, 1, 2, 3, 4], dtype=int32)
+
         """
         if isinstance(obj, ctypes._Pointer):
             # convert pointers to an array of the desired shape
@@ -541,8 +561,27 @@ def as_array(obj, shape=None):
 
 
     def as_ctypes(obj):
-        """Create and return a ctypes object from a numpy array.  Actually
-        anything that exposes the __array_interface__ is accepted."""
+        """
+        Create and return a ctypes object from a numpy array.  Actually
+        anything that exposes the __array_interface__ is accepted.
+
+        Examples
+        --------
+        Create ctypes object from inferred int ``np.array``:
+
+        >>> inferred_int_array = np.array([1, 2, 3])
+        >>> c_int_array = np.ctypeslib.as_ctypes(inferred_int_array)
+        >>> c_int_array
+        <c_long_Array_3 at 0x1071fbed0>
+
+        Create ctypes object from explicit 8 bit unsigned int ``np.array`` :
+
+        >>> exp_int_array = np.array([1, 2, 3], dtype=np.uint8)
+        >>> c_int_array = np.ctypeslib.as_ctypes(exp_int_array)
+        >>> c_int_array
+        <c_ubyte_Array_3 at 0x10755a950>
+
+        """
         ai = obj.__array_interface__
         if ai["strides"]:
             raise TypeError("strided arrays not supported")


Code review comments:
diff_hunk: @@ -541,8 +561,27 @@ def as_array(obj, shape=None):
 
 
     def as_ctypes(obj):
-        """Create and return a ctypes object from a numpy array.  Actually
-        anything that exposes the __array_interface__ is accepted."""
+        """
+        Create and return a ctypes object from a numpy array.  Actually
+        anything that exposes the __array_interface__ is accepted.
+
+        Examples
+        --------
+        Create ctypes object from inferred int ``np.array``:
+
+        >>> inferred_int_array = np.array([1, 2, 3])
+        >>> c_int_array = np.ctypeslib.as_ctypes(inferred_int_array)
+        >>> c_int_array
+        <c_long_Array_3 at 0x1071fbed0>
+
+        Create ctypes object from explicit 8 bit unsigned int ``np.array`` :
+
+        >>> exp_int_array = np.array([1, 2, 3], dtype=np.uint8)
+        >>> c_int_array = np.ctypeslib.as_ctypes(exp_int_array)
+        >>> c_int_array
+        <c_ubyte_Array_3 at 0x10755a950>
path: numpy/ctypeslib.py
text: @user1:
This is fine to merge as-is, but this repr isn't really helpful. Maybe print something else?

@author:
I added a type check and printing the array contents itself.