ewok
ewok

Reputation: 21503

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.

Upvotes: 8

Views: 3625

Answers (1)

9000
9000

Reputation: 40894

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')

Upvotes: 6

Related Questions