Can Python assert be used to check for specific exceptions in a function? For instance, if I have a function that I know will raise a KeyError, can assert detect it? For example:
def get_value(x): lookup = {'one': 1} return lookup[x] assert get_value('two') == KeyError When I run this I just get the KeyError exception. Can assert check something like this? Or is that not what assert is used for?
type()in this case.assert_raises.tryif you wanted to manually catch the error; the function doesn't return the error, it raises it.assertonly works if__debug__is True), not runtime errors or conditions that may or may not arise, or other special events. For those (thinkExceptions) use atryblock