What is assert in Python for?

Asked

Viewed 22,340 times

15

The @Ciganomorrisonmendez gave me a reply in a previous question on Python. And as I’m a beginner in Python still, I didn’t know what the assert that he indicated in the reply.

The excerpt from the code he indicated is this:

assert n >= 0

The question remains: How does the assert and when to use it?

  • 1

    You did some research on this?

  • I found some things in English. From what I understand, it seems to throw an exception if the condition is false. That’s what I think, I’m not sure

  • https://pythonhelp.wordpress.com/2012/09/09/programe-defensivamente-com-assercoes/

  • @Daltonmenezes, wouldn’t it be important to add a few things to the answer? I realized there’s a way to get a message across when the AssertionError is called.

  • 1

    My "last name" is with z at the end. Mendez.

  • By complementing the responses, you can pass a message to Exception using assert condicao, mensagem (ex: `assert n == 1, "The value of n is different from 1")

Show 1 more comment

2 answers

16


The assert is an execution-time check of any condition. If the condition is not true, an Assertionerror exception happens and the program stops.

This is not used for "expected" error conditions, such as a network connection that has not opened. The purpose of assert is to assist in debugging by checking the internal health of the program.

The page Using Assertions Effectively suggests to use to check the types of parameters of a function or method. I would not use for this. The most correct use is to pick up those seemingly impossible error conditions (but end up happening anyway).

If the algorithm itself causes an error in case of inconsistency, I don’t see why to use the assert. In the following code, it is critical that foo() returns a number between 0 and 5, but the code itself ensures that an out-of-range number raises an exception:

n = foo()
s = ["a", "b", "c", "d", "e", "f"][n]

On the other hand, if "n" is critical but it is used for a mathematical operation, which would not fail if n is outside the range, then the assert is interesting:

n = foo()
assert n >= 0 and n <= 5
s = chr(ord('a') + n)
  • Thank you. I had more or less understood what the assert, but just didn’t know in which cases could apply.

7

The assert exists in most programming languages and always has the same function, ensure a condition to continue the implementation of the code.

If the condition is not met, an exception is triggered, and the execution is stopped.

The example you quoted:

assert n >= 0

Will fire an exception if n is not greater than 0.

See this post on SO-en.

UPDATE: An Example, suggested by the IDE - Android Studio, in the code analyzer.

public boolean Upload(String pArqOrigem, String pArqDestino, String DiretorioDestino) {
    boolean status = false;
    FileInputStream srcFileStream =  null;

    try {
        srcFileStream = new FileInputStream(pArqOrigem);

        if (MudarDiretorio(pDiretorioDestino)) {
            myLog.info( "Mudou para: "+pDiretorioDestino);
            status = mFtp.storeFile(pArqDestino, srcFileStream);
        }

        myLog.info( "Upload OK? " + status);
        return status;
    } catch (Exception e) {
        myLog.error( "Erro: Falha ao efetuar Upload. ", e);
        return false;
    } finally {
        try {
            assert srcFileStream != null;
            srcFileStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FDI has documented the use of assert in the finally, because it is necessary to be sure that the object srcFileStream exists before closing it.

Browser other questions tagged

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