I've spent the past year working in Java, where I used assert to ensure that parameters passed into a method fulfilled certain preconditions. I'd like to do the same in Python, but I read here that exceptions are better to use than assert.
This is what I have currently:
if type(x) == List: x = np.array(x) else: err = ("object passed for x is not a numpy.ndarray or a list") assert type(x) is np.ndarray, err err = ("object passed for n is not an integer") assert type(n) is IntType, err err = ("the size of the object passed for x does not equal " "n squared") assert x.size is n**2, err Is there a more elegant and/or Pythonic way to approach this? Should I be writing my own exception class to raise when invalid parameters are passed?
try: x = np.array(x)?try exceptlogic.isto compare numeric values, like you did in your last line. It's possible fora is bto be False even whena == bis True.