1

As suggested in the Python wiki assertions are good for

  • Checking parameter types, classes, or values
  • Checking data structure invariants
  • Checking "can't happen" situations (duplicates in a list, contradictory state variables)
  • After calling a function, to make sure that its return is reasonable

But where is the edge between using assertions and using an 'if' statement with raising exceptions next?

For example.

def some_domain_operation(user, invoice):
    assert isinstance(user, (User, int))
    # Do something.

vs

def some_domain_operation(user, invoice):
    if not isinstance(user, (User, int)):
        raise ValueError()

    # Do something.

I think that using assertions is not reliable (could be disabled by the user), so I could not give a good example, when using assertions is better than using explicit an 'if' with raise next.

What is your opinion about assertions Pn python. Are they crutches?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pavel Patrin
  • 1,630
  • 1
  • 19
  • 33

1 Answers1

1

In my view, there is a big difference between if and assert:

The expression after assert is never true [1]. If it were true, your program might as well stop executing at that point because we do not know what is true any more. [2] They are just a debugging and documentation aid for the developers who look into the source code.

Literally, an assertion says "this is true at this point of program flow. Upon no circumstance would this expression evaluate to false".

Thus, an assert should be considered an invariant. In a correctly written module, no assert will ever be hit. If we consider your case:

assert isinstance(user, (User, int))

If disabling this assert would change the behaviour of the module, it shouldn't be an assert anymore, but raise a TypeError.


[1] ... in a well-behaving, correctly written program.

[2] You should never catch AssertionError, except in the circumstances when you need to catch AssertionError