Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding `numpy.linalg.det` as method to `numpy.matrix`

I wanted to write M.det() instead of numpy.linalg.det(M), so I did this:

numpy.matrix.det = numpy.linalg.det

and it worked.

Is there anything to be said against this proceeding?


Example:

import numpy as np
np.matrix.det = np.linalg.det
M = np.matrix([[1,2],[3,4]])
print M.det()

correct output: -2.0

like image 959
user1445837 Avatar asked Jan 22 '26 13:01

user1445837


1 Answers

This is called monkey patching. It may work in this special case, but it makes your program hard to follow since the det method only exists in your program and is not documented anywhere. Also, it relies on np.matrix implementation details, specifically that it is a pure Python class, and doesn't work for all classes:

>>> numpy.ndarray.det = numpy.linalg.det
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'numpy.ndarray'

I would advise against this; it makes your program harder to read and maintain and there's really no reason not to write from numpy.linalg import det, then det(A) instead of A.det().

like image 161
Fred Foo Avatar answered Jan 25 '26 04:01

Fred Foo