0
0
NumPydata~20 mins

Array protocol and __array__ in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Protocol Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using __array__?

Consider the following Python class that implements the __array__ method. What will be the output when converting an instance to a NumPy array?

NumPy
import numpy as np

class MyArray:
    def __array__(self):
        return np.array([10, 20, 30])

obj = MyArray()
result = np.array(obj)
print(result)
A[10 20 30]
B[[10 20 30]]
C
[[10]
 [20]
 [30]]
DTypeError: Cannot convert object to array
Attempts:
2 left
💡 Hint

The __array__ method returns a NumPy array representation of the object. NumPy uses this to create the array.

data_output
intermediate
2:00remaining
What is the shape of the array returned by __array__?

Given this class with a __array__ method, what is the shape of the resulting NumPy array?

NumPy
import numpy as np

class Custom:
    def __array__(self):
        return np.array([[1, 2], [3, 4], [5, 6]])

obj = Custom()
arr = np.array(obj)
print(arr.shape)
A(1, 6)
B(2, 3)
C(6,)
D(3, 2)
Attempts:
2 left
💡 Hint

Look at the shape of the array returned inside __array__.

🔧 Debug
advanced
2:00remaining
Why does this code raise an error when using __array__?

Examine the code below. Why does calling np.array(obj) raise an error?

NumPy
import numpy as np

class Broken:
    def __array__(self):
        return [1, 2, 'three']

obj = Broken()
np.array(obj)
ANo error, returns array(['1', '2', 'three'], dtype='<U5')
BTypeError because the list contains mixed types that cannot be converted to a numeric array
CAttributeError because __array__ must return a NumPy array, not a list
DValueError because the list length is inconsistent
Attempts:
2 left
💡 Hint

NumPy can create arrays from lists with mixed types by upcasting to strings.

🧠 Conceptual
advanced
2:00remaining
What is the purpose of the __array__ method in NumPy?

Choose the best description of what the __array__ method does in a Python object used with NumPy.

AIt automatically converts all object attributes to arrays
BIt defines how the object converts itself to a NumPy array when passed to np.array()
CIt is used to check if an object is already a NumPy array
DIt prevents the object from being converted to a NumPy array
Attempts:
2 left
💡 Hint

Think about how NumPy uses this method internally.

🚀 Application
expert
3:00remaining
Using __array__ to customize array conversion behavior

Given the class below, what will be the output of np.array(obj)?

NumPy
import numpy as np

class Wrapper:
    def __init__(self, data):
        self.data = data
    def __array__(self, dtype=None):
        arr = np.array(self.data)
        if dtype:
            return arr.astype(dtype)
        return arr * 2

obj = Wrapper([1, 2, 3])
result = np.array(obj, dtype=np.float64)
print(result)
A[2 4 6]
B[2. 4. 6.]
C[1. 2. 3.]
DTypeError because __array__ does not accept dtype argument
Attempts:
2 left
💡 Hint

The __array__ method can accept a dtype argument to customize conversion.