I am writing a class whose __init__ uses either an id OR a slug argument but not both. I’d like to verify that the arguments are as expected. Is it proper, and good-practice to use an assert for the specific purpose of verifying an assumption about arguments, or should I be raising an exception if the arguments aren’t as expected?
e.g.,
def __init__(self, id=None, slug=None):
assert((id or slug) and not (id and slug))
The answer to the original question (“Is it bad practice to use assert to verify internal assumptions in python?”) is decidedly no. That’s the one thing everyone agrees assertions are good for. But what you describe in the question isn’t validation of an internal assumption: It’s validation of external inputs. A
TypeError, aValueError, another builtin exception (or possibly a custom exception, though one should be conservative with those) gives much more useful feedback to users of the API. What’s worse, assertions may be (and, in some environments, usually are) removed completely, meaning your code will silently do the wrong thing.