What is the use of “assert” in Python?

2019-01-03 03:24发布

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?

18条回答
Lonely孤独者°
2楼-- · 2019-01-03 04:04

Python assert is basically a debugging aid which test condition for internal self-check of your code. Assert makes debugging really easy when your code gets into impossible edge cases. Assert check those impossible cases.

Let's say there is a function to calculate price of item after discount :

def calculate_discount(price, discount):
    discounted_price = price - [discount*price]
    assert 0 <= discounted_price <= price
    return discounted_price

here, discounted_price can never be less than 0 and greater than actual price. So, in case the above condition is violated assert raises an Assertion Error, which helps the developer to identify that something impossible had happened.

Hope it helps :)

查看更多
beautiful°
3楼-- · 2019-01-03 04:05
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.

查看更多
叼着烟拽天下
4楼-- · 2019-01-03 04:05
>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)

>>> #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 "<pyshell#52>", line 1, in <module>
    assert test_us
AssertionError
>>> 
查看更多
唯我独甜
5楼-- · 2019-01-03 04: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.

查看更多
Evening l夕情丶
6楼-- · 2019-01-03 04:14

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 "<pyshell#11>", line 1, in <module>
             #assert 0>1
             #AssertionError
查看更多
走好不送
7楼-- · 2019-01-03 04:15

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 <module>    
    print KelvinToFahrenheit(-5)    
  File "test.py", line 4, in KelvinToFahrenheit    
    assert (Temperature >= 0),"Colder than absolute zero!"    
AssertionError: Colder than absolute zero!    
查看更多
登录 后发表回答