Using assert
, you can easily test a condition without needing an if/raise
:
assert condition, msg
is the same as
if not condition:
raise AssertionError(msg)
My question is whether it is possible to use assert
to raise different types of Errors
. For example, if you are missing a particular environment variable, it would be useful to get back an EnvironmentError
. This can be done manually with either a try/catch
or a similar if/raise
as before:
if not variable in os.environ:
raise EnvironmentError("%s is missing!" % variable)
or
try:
assert variable in os.environ
except:
raise EnvironmentError("%s is missing!" % variable)
But I'm wondering if there is a shortcut of some type that I haven't been able to find, or if there is some workaround to be able to have multiple except
s up the stack.
The AssertionError Exception If the condition of an assert statement evaluates to false, then assert raises an AssertionError .
TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.
The assert Statement When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
In python there are three types of errors; syntax errors, logic errors and exceptions.
The built-in assert
is a debug feature, it has a narrow use, and can even be stripped from code if you run python -O
.
If you want to raise various exceptions depending on conditions with one-liner expressions, write a function!
assert_env(variable in os.environ)
Or even
assert_env_var(variable) # knows what to check
If you want a super-generic / degenerate case, consider a function that accepts everything as parameters (possibly with some default values):
my_assert(foo == bar, FooException, 'foo was not equal to bar')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With