user1445837
user1445837

Reputation: 33

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

Upvotes: 3

Views: 374

Answers (1)

Fred Foo
Fred Foo

Reputation: 363627

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().

Upvotes: 2

Related Questions