python: use assert to raise different Error types

Viewed 1873

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.

1 Answers
Related