RadiantHex
RadiantHex

Reputation: 25557

Using assert within methods - Python

is it bad practice to use asserts within methods?

e.g.

def add(x, y):
    assert isinstance(x, int) and isinstance(y, int)
    return x + y

Any ideas?

Upvotes: 2

Views: 914

Answers (4)

Andrey Sboev
Andrey Sboev

Reputation: 7682

It's ok because you may run your application with -O command line option and no code would be generated for your assert statement see here

Update:

But also you should handle all errors anyway. Otherwise after stripping assertions unhandled exceptions may occur. (as McConnell recomended. See his citations here)

Upvotes: 2

user2665694
user2665694

Reputation:

Instead of using assertions and raising Assertion exception...better perform proper checks using instance() and raise a proper TypeError.

Upvotes: 0

user2665694
user2665694

Reputation:

It's not but if your code contains more assert statements than your actual code then I would be angry.

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46607

Not at all.

In your sample, provided you have documented that add expects integers, asserting this constraint at the beginning of the method is actually great practice.

Just imagine the other choices you have and how bad they are:

  • don't verify your arguments. This means, the method will fail later with a strange backtrace that will presumably confuse the caller and force him to have a look at the implementation of add to get a hint what's going on.
  • be nice and try to convert the input to int - very bad idea, users will keep wondering why add(2.4,3.1) keeps returning 5.

Upvotes: 6

Related Questions