views:

62

answers:

1

I found this today while looking at a library for an API .

def my_function(self, required_param=None):
    assert(required_param)
    ... Do cool function stuff

Wouldn't it be easier to do this:

def my_function(self, required_param):
    ... Do cool function stuff

Or, am I missing something?

The assert() of course gives you one unified exception that could come up, but unless you wanted this function to fail silently to do something in that case, wouldn't you rather have it break loudly so that you can catch such errors early on? I've never understood why people use assertions in production code. Perhaps, I will after I get some answers for this.

+1  A: 

The only reason I can imagine for the situation you've described is to also reject False, 0, [], (,), etc. But that doesn't make sense to assert against the default value.

If the author wasn't intending to reject other false-ish values, then that assert is even more dubious.

Mark Rushakoff
But in that case, why not `if not required_param: ...` I too think this is sketchy. Maybe the author forgot to take it out? Or replace it with a more informative exception?
gilesc