Python, difference between assert and raise?

Asked

Viewed 8,743 times

20

I came across a question with the structures raise and assert python.

In the code below shows the implementation of structures forcing an error if the number passed is negative.

def is_neg_assert(int):
    assert (int >= 0), "Número negativo"

def is_neg_raise(int):
    if int < 0:
        raise "Número negativo"

Both will force the error if the value passed is less than 0.

What is the difference of use and implementation between assert and raise

  • +1 is the kind of question I like on this site

  • I think this question answers itself, since it has the code examples

  • 1

    @jsbueno I think does not auto-respond no. It does not seem so obvious when you use an Exception with a if

  • @jsbueno, the purpose of the question, is to know why there are both "error" structures, and how to implement them. Taking into account the answer, it can be said that it is not right to use the raise in one condition, this structure would be geared more to use in declaring abstract methods in classes (from what I understood).

  • If you have said that, the answer is not good - raise causes a deliberate error and has hundreds of use cases in everyday life - far from just indicating abstract methods. But the "difference" between assert and raise is in the code snippets of the question. Maybe the question is not well written then.

Show 1 more comment

1 answer

20


raise is intended to invoke a Exception at the right time. In the same way as other languages when we use throw new Exception, the exception is invoked the moment we call raise.

Example:

 raise Exception('Invoquei')


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Invoquei

the assert in turn makes a statement and, if it fails (ie, returns False), invokes an Exception.

This statement occurs as follows: If true, the next line continues to run normally. If False, the exception is cast, with the message you passed as critical of the statement failure.

Example:

a = 1 + 1

assert a == 2, 'Conta está errada'

assert a == 3, 'Conta está errada' #Exceção é lançada aqui, pois é falso

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: Conta errada

I believe that in your case, because it is a simple example, the logic used to critique the argument passed to the function, makes no difference. The two are appropriate.

In my view the most striking difference between the two is the fact that the assert will always need a returning condition False to invoke an exception. The raise in turn, it is the mechanism responsible exactly for calling an exception, regardless of the condition.

An example of what I’m talking about raise does not need to condition is the following: Imagine a class that you created to be always derived and have a certain superscript method. If it is not overwritten, I need to cast an exception warning that it is necessary to overwrite it. I would not use assert, but raise.

Behold:

  class abstrata(object):

       def metodo(self):
            raise "Esse método precisa ser implementado na classe filha"


 class concreta(abstrata):

      def metodo(self):

          return "implementei com sucesso"

Realize that in this scenario raise has its purpose completely different from assert, since I simply want to report an error independent of conditions

  • 1

    +1 I particularly liked the last example. But concreta should not inherit from abstrata - instead of object?

  • It’s true @mgibsonbr, by the time I answered I can understand the vacilo, right? Thanks for warning

  • @mgibsonbr I’m glad you liked the example. I don’t even program in Python yet and could explain. This means that by studying Python, I am progressing to a different level of PHP, kkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.