Program Tip

파이썬에서“assert”의 사용은 무엇입니까?

programtip 2020. 9. 28. 09:54
반응형

파이썬에서“assert”의 사용은 무엇입니까?


나는 몇 가지 소스 코드를 읽고 여러 곳에서 assert.

정확히 무엇을 의미합니까? 그 사용법은 무엇입니까?


assert진술은 거의 모든 프로그래밍 언어에 존재합니다. 나중에 다른 작업의 부작용이 아니라 원인이 분명한 프로그램 초기에 문제를 감지하는 데 도움이됩니다.

당신이 할 때 ...

assert condition

... 프로그램에 해당 조건을 테스트하도록 지시하고 조건이 거짓이면 즉시 오류를 트리거합니다.

Python에서는 대략 다음과 같습니다.

if not condition:
    raise AssertionError()

Python 셸에서 시도해보세요.

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

어설 션은 선택적 메시지를 포함 할 수 있으며 인터프리터를 실행할 때이를 비활성화 할 수 있습니다.

어설 션이 실패한 경우 메시지를 인쇄하려면 :

assert False, "Oh no! This assertion failed!"

마십시오 하지 전화 괄호를 사용 assert하는 함수처럼. 진술입니다. 그렇다면 첫 번째 매개 변수로 튜플을 사용하여을 assert(condition, message)실행할 것 assert입니다 (condition, message).

비활성화에 관해서 python는 최적화 모드에서 실행할 때 __debug__is가 False이면 assert 문이 무시됩니다. -O플래그를 전달하십시오 .

python -O script.py

관련 문서는 여기참조 하십시오 .


괄호를 조심하십시오. 위에서 지적 된 바와 같이, 파이썬 3에서, assert여전히 문이다 그렇게 유추와, print(..)하나는 동일한를 추정 할 수있다 assert(..)또는 raise(..)그러나 당신은 안된다.

이는 다음과 같은 이유로 중요합니다.

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

달리 작동하지 않습니다

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

첫 번째가 작동하지 않는 이유는로 bool( (False, "Houston we've got a problem") )평가되기 때문 True입니다.

assert(False)에서 이들은 False내용을 평가하는 주위의 중복 괄호 일뿐 입니다. 그러나 assert(False,)괄호를 사용하면 이제 튜플이되고 비어 있지 않은 튜플 True은 부울 컨텍스트에서 평가됩니다 .


다른 답변에서 언급했듯이 assert주어진 조건이 참이 아닌 경우 예외를 던지는 것과 유사합니다. 중요한 차이점은 최적화 옵션을 사용하여 코드를 컴파일하면 assert 문이 무시된다는 것입니다. 문서는 그가 말한다 assert expression더 나은에 해당하는 것으로 설명 될 수있다

if __debug__:
   if not expression: raise AssertionError

이는 코드를 철저히 테스트 한 다음 어설 션 사례가 실패하지 않는 것이 만족 스러울 때 최적화 된 버전을 릴리스하려는 경우 유용 할 수 있습니다. 최적화가 켜져 있으면 __debug__변수가 False가되고 조건 평가가 중지됩니다. 이 기능은 단언에 의존하고 있고 그들이 사라 졌다는 것을 깨닫지 못하는 경우에도 알아낼 수 있습니다.


다른 사람들은 이미 문서에 대한 링크를 제공했습니다.

대화 형 셸에서 다음을 시도 할 수 있습니다.

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

첫 번째 문은 아무 작업도 수행하지 않고 두 번째 문은 예외를 발생시킵니다. 이것이 첫 번째 힌트입니다. 어설 션은 코드의 주어진 위치 (보통, 함수의 시작 (전제 조건) 및 끝 (사후 조건))에서 참이어야하는 조건을 확인하는 데 유용합니다.

어설 션은 실제로 계약에 의한 프로그래밍과 밀접한 관련이 있으며 이는 매우 유용한 엔지니어링 관행입니다.

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


Python에서 어설 션의 목표는 개발자에게 프로그램의 복구 할 수없는 오류 를 알리는 것입니다 .

어설 션은 사용자가 수정 조치를 취하거나 다시 시도 할 수있는 "파일을 찾을 수 없음"과 같은 예상 오류 조건을 알리기위한 것이 아닙니다.

그것을 보는 또 다른 방법은 어설 션이 코드의 내부 자체 검사 라고 말하는 것입니다 . 코드에서 일부 조건을 불가능하다고 선언하여 작동 합니다. 이러한 조건이 유지되지 않으면 프로그램에 버그가 있음을 의미합니다.

프로그램에 버그가없는 경우 이러한 조건은 발생하지 않습니다. 그러나 이들 중 하나 발생하면 프로그램은 정확히 어떤 "불가능한"조건이 트리거되었는지 알려주는 어설 션 오류와 함께 충돌합니다. 이렇게하면 프로그램의 버그를 훨씬 쉽게 추적하고 수정할 수 있습니다.

다음은 내가 작성한 Python의 주장에 대한 자습서 의 요약입니다 .

Python의 assert 문은 런타임 오류를 처리하는 메커니즘이 아니라 디버깅 보조 도구입니다. 어설 션 사용의 목표는 개발자가 버그의 근본 원인을 더 빨리 찾을 수 있도록하는 것입니다. 프로그램에 버그가 없으면 어설 션 오류가 발생해서는 안됩니다.


assert 문에는 두 가지 형식이 있습니다.

간단한 형식 assert <expression>은 다음과 같습니다.

if __​debug__:
    if not <expression>: raise AssertionError

확장 형식 assert <expression1>, <expression2>은 다음과 같습니다.

if __​debug__:
    if not <expression1>: raise AssertionError, <expression2>

어설 션은 버그를 잡을 목적으로 프로그램의 내부 상태가 프로그래머가 예상 한대로인지 확인하는 체계적인 방법입니다. 아래 예를 참조하십시오.

>>> 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 "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>> 

문서에서 :

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

여기에서 더 읽을 수 있습니다 : http://docs.python.org/release/2.5.2/ref/assert.html


다음은 간단한 예입니다. 파일에 저장합니다 (b.py라고 가정 해 보겠습니다).

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


chkassert('a')

결과는 $python b.py

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

assert 이후의 문이 true이면 프로그램은 계속되지만 assert 이후의 문이 false이면 프로그램은 오류를 발생시킵니다. 그렇게 간단합니다.

예 :

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

C2 Wiki 에 간결하게 요약되어 있습니다 .

어설 션은 프로그램의 특정 지점에있는 부울 표현식으로, 프로그램 에 버그가없는 한입니다.

assert명령문을 사용하여 특정 프로그램 지점에서 코드에 대한 이해를 문서화 할 수 있습니다 . 예를 들어 입력 (전제 조건), 프로그램 상태 (불변) 또는 출력 (사후 조건)에 대한 가정 또는 보증을 문서화 할 수 있습니다.

귀하의 주장이 실패 할 경우, 이것은 귀하 (또는 귀하의 후임자)에게 프로그램을 작성할 때 잘못 이해했으며 버그가있을 가능성이 있다는 경고입니다.

더 많은 정보를 위해 John Regehr는 Use of Assertions 에 대한 멋진 블로그 게시물을 가지고 있는데 , 이는 Python assert문장 에도 적용됩니다 .


예약 함수가 파이썬에서 무엇을하는지 정확히 알고 싶다면 다음을 입력하십시오. help(enter_keyword)

예약 된 키워드를 입력하는 경우 문자열로 입력해야합니다.


assert진술은 거의 모든 프로그래밍 언어에 존재합니다. 나중에 다른 작업의 부작용이 아니라 원인이 분명한 프로그램 초기에 문제를 감지하는 데 도움이됩니다. 그들은 항상 True조건을 기대합니다 .

다음과 같이 할 때 :

assert condition

프로그램에 해당 조건을 테스트하고 거짓이면 즉시 오류를 트리거하도록 지시합니다.

Python에서 assertexpression 은 다음과 같습니다.

if __debug__:
    if not <expression>: raise AssertionError

확장 표현식을 사용하여 선택적 메시지 를 전달할 수 있습니다 .

if __debug__:
    if not (expression_1): raise AssertionError(expression_2)

Python 인터프리터에서 시도해보십시오.

>>> assert True # Nothing happens because the condition returns a True value.
>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

There are some caveats to seen before using them mainly for those who deem to toggles between the assert and if statements. The aim to use assert is on occasions when the program verifies a condition and return a value that should stop the program immediately instead of taking some alternative way to bypass the error:

1. Parentheses

As you may have noticed, the assert statement uses two conditions. Hence, do not use parentheses to englobe them as one for obvious advice. If you do such as:

assert (condition, message)

Example:

>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?

You will be running the assert with a (condition, message) which represents a tuple as the first parameter, and this happens cause non-empty tuple in Python is always True. However, you can do separately without problem:

assert (condition), "message"

Example:

>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.

2. Debug purpose

If you are wondering regarding when use assert statement. Take an example used in real life:

* When your program tends to control each parameter entered by the user or whatever else:

def loremipsum(**kwargs):
    kwargs.pop('bar') # return 0 if "bar" isn't in parameter
    kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
    assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())

* Another case is on math when 0 or non-positive as a coefficient or constant on a certain equation:

def discount(item, percent):
    price = int(item['price'] * (1.0 - percent))
    print(price)
    assert (0 <= price <= item['price']),\
            "Discounted prices cannot be lower than 0 "\
            "and they cannot be higher than the original price."

    return price

* or even a simple example of a boolean implementation:

def true(a, b):
    assert (a == b), "False"
    return 1

def false(a, b):
    assert (a != b), "True"
    return 0

3. Data processing or data validation

The utmost importance is to not rely on the assert statement to execute data processing or data validation because this statement can be turned off on the Python initialization with -O or -OO flag – meaning value 1, 2, and 0 (as default), respectively – or PYTHONOPTIMIZE environment variable.

Value 1:

* asserts are disabled;

* bytecode files are generated using .pyo extension instead of .pyc;

* sys.flags.optimize is set to 1 (True);

* and, __debug__ is set to False;

Value 2: disables one more stuff

* docstrings are disabled;

Therefore, using the assert statement to validate a sort of expected data is extremely dangerous, implying even to some security issues. Then, if you need to validate some permission I recommend you raise AuthError instead. As a preconditional effective, an assert is commonly used by programmers on libraries or modules that do not have a user interact directly.


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 :)


My short explanation is:

  • assert raises AssertionError if expression is false, otherwise just continues the code, and if there's a comma whatever it is it will be AssertionError: whatever after comma, and to code is like: raise AssertionError(whatever after comma)

A related tutorial about this:

https://www.tutorialspoint.com/python/assertions_in_python.htm


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!    

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.


>>>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
>>> 

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

참고URL : https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python

반응형