The array protocol lets objects tell NumPy how to convert themselves into arrays. The __array__ method is a simple way to make your object behave like a NumPy array.
Array protocol and __array__ in NumPy
class YourClass: def __array__(self, dtype=None): # Return a NumPy array representation of your data import numpy as np data = ... # your data here if dtype is not None: return np.array(data, dtype=dtype) else: return np.array(data)
The __array__ method should return a NumPy array.
The optional dtype argument lets NumPy request a specific data type.
import numpy as np class SimpleData: def __init__(self, values): self.values = values def __array__(self, dtype=None): if dtype is not None: return np.array(self.values, dtype=dtype) return np.array(self.values) obj = SimpleData([1, 2, 3]) print(np.array(obj))
import numpy as np class EmptyData: def __array__(self, dtype=None): return np.array([]) obj = EmptyData() print(np.array(obj))
import numpy as np class SingleValueData: def __init__(self, value): self.value = value def __array__(self, dtype=None): return np.array([self.value], dtype=dtype) if dtype is not None else np.array([self.value]) obj = SingleValueData(42) print(np.array(obj))
import numpy as np class DataAtEdges: def __init__(self, values): self.values = values def __array__(self, dtype=None): return np.array(self.values, dtype=dtype) if dtype is not None else np.array(self.values) obj = DataAtEdges([0, 1, 2, 3, 4]) print(np.array(obj))
This program shows how a custom object with a __array__ method can be converted to a NumPy array automatically. It prints the original data, the converted array, and calculates the mean using NumPy.
import numpy as np class CustomData: def __init__(self, data_list): self.data_list = data_list def __array__(self, dtype=None): # Convert internal list to numpy array if dtype is not None: return np.array(self.data_list, dtype=dtype) return np.array(self.data_list) # Create an object with some data custom_object = CustomData([10, 20, 30, 40]) # Print the object data before conversion print('Original data in object:', custom_object.data_list) # Convert to numpy array using the array protocol numpy_array = np.array(custom_object) print('Converted to numpy array:', numpy_array) # Use numpy functions on the converted array mean_value = np.mean(custom_object) print('Mean of data:', mean_value)
The __array__ method lets NumPy know how to convert your object to an array quickly.
Time complexity depends on the size of your data because it copies data into a new array.
Space complexity is also proportional to the data size since a new array is created.
A common mistake is forgetting to handle the optional dtype argument, which can cause errors when NumPy requests a specific type.
Use __array__ when you want seamless integration with NumPy functions. For simple conversions, you might also use np.array(your_data) directly if your data is already array-like.
The __array__ method allows custom objects to behave like NumPy arrays.
It helps NumPy convert your data automatically for fast numerical operations.
Remember to handle the optional dtype argument for flexibility.
Practice
__array__ method in a custom Python class when working with NumPy?Solution
Step 1: Understand the role of
The__array____array__method is designed to let custom objects tell NumPy how to convert them into arrays.Step 2: Identify the main purpose
This method enables automatic conversion, so NumPy can work with the data efficiently.Final Answer:
To allow the object to be converted automatically into a NumPy array -> Option BQuick Check:
Conversion to NumPy array [OK]
- Confusing __array__ with data type definition
- Thinking __array__ performs calculations
- Assuming __array__ creates plots
__array__ method in a custom class to return a NumPy array?Solution
Step 1: Check method signature
The__array__method should accept an optionaldtypeargument for flexibility.Step 2: Verify return type
It must return a NumPy array, so usingnp.array(self.data, dtype=dtype)is correct.Final Answer:
def __array__(self, dtype=None): return np.array(self.data, dtype=dtype) -> Option DQuick Check:
Correct signature and return type [OK]
- Omitting dtype parameter
- Returning list instead of np.array
- Using tolist() which returns Python list
print(np.array(obj))?
import numpy as np
class MyData:
def __init__(self):
self.data = [1, 2, 3]
def __array__(self, dtype=None):
return np.array(self.data, dtype=dtype)
obj = MyData()
print(np.array(obj))Solution
Step 1: Understand __array__ method behavior
The method returns a NumPy array created from the list [1, 2, 3].Step 2: Predict np.array conversion
Callingnp.array(obj)triggersobj.__array__(), returningnp.array([1, 2, 3]), which prints as [1 2 3].Final Answer:
[1 2 3] -> Option AQuick Check:
Custom __array__ returns array [1 2 3] [OK]
- Expecting Python list output with commas
- Thinking output is nested array
- Assuming TypeError due to custom class
__array__ method implementation?
def __array__(self):
return self.data.astype(float)Solution
Step 1: Check method signature
The__array__method should accept an optionaldtypeargument to allow flexible conversions.Step 2: Identify missing dtype parameter
This method lacks thedtype=Noneparameter, so it cannot handle dtype requests from NumPy.Final Answer:
It does not accept the optional dtype argument -> Option AQuick Check:
Missing dtype parameter [OK]
- Forgetting dtype argument
- Thinking astype cannot convert types
- Returning list instead of array
__array__ method that returns a NumPy array. You want to ensure that when you call np.array(obj, dtype=np.float64), the returned array respects the requested dtype. How should you modify the __array__ method?Solution
Step 1: Understand dtype propagation
NumPy passes the requested dtype to__array__as an argument; the method must accept it.Step 2: Implement dtype-aware conversion
Returnnp.array(self.data, dtype=dtype)so the requested dtype is applied correctly.Final Answer:
def __array__(self, dtype=None): return np.array(self.data, dtype=dtype) -> Option CQuick Check:
Accept dtype and pass to np.array [OK]
- Ignoring dtype argument
- Hardcoding dtype inside method
- Not accepting dtype parameter
Ready to prove it?
Pass the test and this pattern moves unknown
