Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: use assert to raise different Error types

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 excepts up the stack.

like image 952
ewok Avatar asked Jul 17 '17 18:07

ewok


People also ask

What error does assert raise?

The AssertionError Exception If the condition of an assert statement evaluates to false, then assert raises an AssertionError .

How do you raise error type in Python?

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.

Does Python assert raise an exception?

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.

What are the 3 types of errors in Python?

In python there are three types of errors; syntax errors, logic errors and exceptions.


1 Answers

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')
like image 153
9000 Avatar answered Oct 08 '22 05:10

9000