What is the best way to verify that past parameters are valid in Python?

I spent the last year working in Java, where I used assertto ensure that the parameters passed to the method met certain preconditions. I would like to do the same in Python, but I read here that exceptions are better to use than assert.

This is what I have:

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 get closer to this? Do I have to write my own exception class to raise when passing invalid parameters?

+4
source share
4 answers

don't limit yourself

, , .. , , . , . EAFP-Apporach.

, , , .

assert

assert , (python -O).

+2

-, , , if isinstance(x, list), type(x). , , (. isinstance() type() python).

-, , x ? ? - ? Sequence ? , np.array? Python , "duck typing" ; , .

:

from collections import Sequence

def some_func(x, n):
    if not isinstance(x, (Sequence, np.ndarray)):
        raise TypeError('x must be a sequence or numpy array')
    x = np.ndarray(x)
    if x.size != n ** 2:  # possible TypeError if n**2 doesn't make sense
        raise ValueError('x must be {} long'.format(n ** 2))
    ...

a TypeError ( x n), ValueError (x - , ), , AssertionError, .

+1

Python . , , , , .

, , .

, Python Java. Java ( - - / , ). Python , , , , ( ) .

. /, - , - , .

0

Python ,

,

()

, try: except:, .

https://docs.python.org/2/glossary.html

, , C/++:)

, - . , numpy. IMO - catch , , .

import numpy as np

def my_np_array(l, n):
    # if you want to catch exceptions outside of the function 
    # I would just not check 'l' and not catch anything, np.array accepts 
    # pretty much anything anyway
    try:
        x = np.array(l)
    except TypeError:
        print 'Parameter l is invalid'
        return None

    if x.size != n**2:
        raise TypeError("n^2 must be equal to x.size")

    return x
0

All Articles