8

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
  • 7
    Assert is a debug time feature, that can be disabled or enabled using a special command line flag. You can write a version that does what you need as a function, accepting an optional error class. However, I would generally advise writing it purely rather than as a function that you delegate to, it sounds like sanitising code rather than development asserts Commented Jul 17, 2017 at 18:52

1 Answer 1

6

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.