What is the use of “assert” in Python?

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

I have been reading some source code and in several places I have seen the usage of assert.

What does it mean exactly? What is its usage?

回答1:

The assert statement exists in almost every programming language. When you do...

assert condition 

... you're telling the program to test that condition, and trigger an error if the condition is false.

In Python, it's roughly equivalent to this:

if not condition:     raise AssertionError() 

Try it in the Python shell:

>>> assert True # nothing happens >>> assert False Traceback (most recent call last):   File "", line 1, in  AssertionError 

Assertions can include an optional message, and you can disable them when you're done debugging. See here for the relevant documentation.



回答2:

Watch out for the parentheses. As has been pointed out above, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is important because:

assert(2 + 2 == 5, "Houston we've got a problem") 

won't work, unlike

assert 2 + 2 == 5, "Houston we've got a problem" 

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.



回答3:

As other answers have noted, assert is similar to throwing an exception if a given condition isn't true. An important difference is that assert statements get ignored if you compile your code with the optimization option. The documentation says that assert expression can better be described as being equivalent to

if __debug__:    if not expression: raise AssertionError 

This can be useful if you want to thoroughly test your code, then release an optimized version when you're happy that none of your assertion cases fail - when optimization is on, the __debug__ variable becomes False and the conditions will stop getting evaluated. This feature can also catch you out if you're relying on the asserts and don't realize they've disappeared.



回答4:

Others have already given you links to documentation.

You can try the following in a interactive shell:

>>> assert 5 > 2 >>> assert 2 > 5 Traceback (most recent call last):   File "", line 1, in  builtins.AssertionError: 

The first statement does nothing, while the second raises an exception. This is the first hint: asserts are useful to check conditions that should be true in a given position of your code (usually, the beginning (preconditions) and the end of a function (postconditions)).

Asserts are actually highly tied to programming by contract, which is a very useful engineering practice:

http://en.wikipedia.org/wiki/Design_by_contract.



回答5:

The goal of an assertion in Python is to inform developers about unrecoverable errors in a program.

Assertions are not intended to signal expected error conditions, like “file not found”, where a user can take corrective action (or just try again).

Another way to look at it is to say that assertions are internal self-checks in your code. They work by declaring some conditions as impossible in your code. If these conditions don’t hold that means there’s a bug in the program.

If your program is bug-free, these conditions will never occur. But if one of them does occur the program will crash with an assertion error telling you exactly which “impossible” condition was triggered. This makes it much easier to track down and fix bugs in your programs.

Here’s a summary from a tutorial on Python’s assertions I wrote:

Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program.



回答6:

The assert statement has two forms.

The simple form, assert , is equivalent to

The extended form, assert , , is equivalent to



回答7:

Assertions are a systematic way to check that the internal state of a program is as the programmer expected, with the goal of catching bugs. See the example below.

>>> number = input('Enter a positive number:') Enter a positive number:-1 >>> assert (number > 0), 'Only positive numbers are allowed!' Traceback (most recent call last):   File "", line 1, in  AssertionError: Only positive numbers are allowed! >>>  


回答8:

From docs:

Assert statements are a convenient way to insert debugging assertions into a program 

Here you can read more: http://docs.python.org/release/2.5.2/ref/assert.html



回答9:

Here is a simple example, save this in file (let's say b.py)

def chkassert(num):     assert type(num) == int   chkassert('a') 

and the result when $python b.py

Traceback (most recent call last):   File "b.py", line 5, in      chkassert('a')   File "b.py", line 2, in chkassert     assert type(num) == int AssertionError 


回答10:

If you ever want to know exactly what a reserved function does in python, type in help(enter_keyword)

Make sure if you are entering a reserved keyword that you enter it as a string.



回答11:

if the statement after assert is true then the program continues , but if the statement after assert is false then the program gives an error. Simple as that.

e.g.:

assert 1>0   #normal execution assert 0>1   #Traceback (most recent call last):              #File "", line 1, in               #assert 0>1              #AssertionError 


回答12:

def getUser(self, id, Email):      user_key = id and id or Email      assert user_key 

Can be used to ensure parameters are passed in the function call.



回答13:

format : assert Expression[,arguments] When assert encounters a statement,Python evaluates the expression.If the statement is not true,an exception is raised(assertionError). If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Example:

def KelvinToFahrenheit(Temperature):         assert (Temperature >= 0),"Colder than absolute zero!"         return ((Temperature-273)*1.8)+32     print KelvinToFahrenheit(273)     print int(KelvinToFahrenheit(505.78))     print KelvinToFahrenheit(-5)     

When the above code is executed, it produces the following result:

32.0 451 Traceback (most recent call last):       File "test.py", line 9, in          print KelvinToFahrenheit(-5)       File "test.py", line 4, in KelvinToFahrenheit         assert (Temperature >= 0),"Colder than absolute zero!"     AssertionError: Colder than absolute zero!     


回答14:

Shortcuts to grok 'assert'.

assert performs as a Checkpoint,

If it functions well, continue;

otherwise raise an alert.



回答15:

>>>this_is_very_complex_function_result = 9 >>>c = this_is_very_complex_function_result >>>test_us = (c >> #first we try without assert >>>if test_us == True:     print("YES! I am right!") else:     print("I am Wrong, but the program still RUNS!")  I am Wrong, but the program still RUNS!   >>> #now we try with assert >>> assert test_us Traceback (most recent call last):   File "", line 1, in      assert test_us AssertionError >>>  


回答16:

Basically the assert keyword meaning is that if the condition is not true then it through an assertionerror else it continue for example in python.

code-1

a=5  b=6  assert a==b 

OUTPUT:

assert a==b  AssertionError 

code-2

a=5  b=5  assert a==b 

OUTPUT:

Process finished with exit code 0 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!