开发者

Python method's arguments validation, ArgError

When programming in C# I usually write following arguments validation code:

void Process(object item) {
    if (item == null) throw ArgumentNullException();
    // code
}

Is it 'Pythonic' to do similar validation in Python? I really don't want anybody pass 开发者_如何学JAVANone to Process method. What type of Python Exception should I use? (There are no standard ArgError or something like this)

def Process(item):
  if item == None: raise ArgNoneError('item')
  # code

Thanks


Usually, you'd just try to make do with the arguments you got -- if someone passes None to your function it will fail anyway. There is no need to add complexity to your code without any benefit. Quite the contrary -- often such tests prevent your code from working for cases it would work fine wwithout the tests.

If you want to raise some error anyway, use TypeError -- it is meant for this purpose.


Use TypeError:

exception TypeError

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜