Skip to main content
Data Science Wizardry Blog by Attila Vajda

How does + work in NumPy?

How + translates to __add__ in NumPy?

import numpy as np
result = np.array([1, 2, 3, 4, 5]) + np.array([1, 1, 1, 1, 1])

I looked for "+" sign in the NumPy codebase

I think I found it, this is so cool:

def __add__(self: Array, other: Union[int, float, Array], /) -> Array:
	"""
	Performs the operation __add__.
	"""
		other = self._check_allowed_dtypes(other, "numeric", "__add__")
		if other is NotImplemented:
			return other
		self, other = self._normalize_two_args(self, other)
		res = self._array.__add__(other._array)
		return self.__class__._new(res)
result = self._array + other._array

What is _ and can the original implementation be refactored to this simple one liner?

Looking up the implementation in the codebase feels like the next level of programming, for me.

I can ask questions about implemented code snippets - this is awesome! 🎉🐍 Which is an answer to my question of how to contribute to Datascience libraries as a beginner

How + translates to __add__ in NumPy? #

Dunder methods

numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)

3.3.8. Emulating numeric types

Python Operator Overloading and the Python Data model

I still don't get it. How + becomes __add__

I found a more accurate question: