What Is the Use of "Assert" in Python

What is the use of assert in Python?

The assert statement exists in almost every programming language. It has two main uses:

  1. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an Exception if not caught early on.

  2. It works as documentation for other developers reading the code, who see the assert and can confidently say that its condition holds from now on.

When you do...

assert condition

... you're telling the program to test that condition, and immediately 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 "<stdin>", line 1, in <module>
AssertionError

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

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

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

See here for the relevant documentation.

Best practice for using assert?

To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:

class LessThanZeroException(Exception):
pass

class variable(object):
def __init__(self, value=0):
self.__x = value

def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')

self.__x = value

def __get__(self, obj, objType):
return self.__x

class MyClass(object):
x = variable()

>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero

How to properly use assertion in python?

Do you mean something like this?

a = 1
b = 2
c = 3

assert b > a and c > b and a > c, 'Error: a is not greater than c'

Output:

Traceback (most recent call last):
File "main.py", line 6, in <module>
assert b > a and c > b and a > c, 'Error: a is not greater than c'
AssertionError: Error: a is not greater than c

something like this:- check c only when b > a is true and check a > c only both are true. And after assertion executes multiple statements like:- log the info and print the info etc..

You can use several assert statements one after another, like you'ld write several if statements under each other, except you've to take into account that your asserts can raise an exception, which you need to take care of. This way you can simply control the execution flow, and print/log whatever you need... For example something like this:

def make_comperations(a, b, c = None): # note c is optional
assert c is not None, 'Error: c is None'
assert b > a, 'Error: a is not greater than b'
assert c > a, 'Error: c is not greater than a'

try:
make_comperations(1, 2, 3) # ok
make_comperations(1, 2) # error
make_comperations(1, 2, 0) # error, but won't be executed since the line above will throw an exception
print("All good!")
except AssertionError as err:
if str(err) == 'Error: c is None':
print("Log: c is not given!")
if str(err) == 'Error: a is not greater than b':
print("Log: b > a error!")
elif str(err) == 'Error: c is not greater than a':
print("Log: c > a error!")

Output:

Log: c is not given!

When should I use 'assert' in Python?

The assertion is to make sure that objects, results, return, etc are what we expect them to be. Though they can be used for variable's type checking, that's not what their real purpose is and it gets repetitive.

In your case, I would suggest to use python EAFP way of doing things. Let the operation be performed on function input and catch the exception if it's not what is expected. From Python glossary :

EAFP: Easier to ask for forgiveness than permission. This common Python
coding style assumes the existence of valid keys or attributes and
catches exceptions if the assumption proves false. This clean and fast
style is characterized by the presence of many try and except
statements. The technique contrasts with the LBYL(Look before you leap) style common to many
other languages such as C.

A quick example:

def f(x):
"""If x is str a TypeError is raised"""
return 1 + x

try:
f('a')
except TypeError as e:
# something here or raise a custom exception
raise

What is the advantage if any of using assert over an if-else condition?

According to the documentation, assert x == "hello" is equivalent to

if __debug__:
if not (x == "hello"):
raise AssertionError

__debug__ is a read-only variable that is set to True if Python is not run with the -O flag, and the compiler can omit the assertion check altogether when -O is used (rather than constantly checking the value of __debug__ at run-time).

Use assertions for debugging and testing, to quickly end your program if an assertion fails. Use if statements for code that must run to enable the rest of your code to work properly.

What does the assert statement do?

You are obviously using Selenium together with Python. Anyway, the assert keyword can be found in many programming languages.

For a language independent explanation of assert, have a look at Wikipedia:

In computer programming, specifically when using the imperative programming paradigm, an assertion is a predicate (a Boolean-valued function over the state space, usually expressed as a logical proposition using the variables of a program) connected to a point in the program, that always should evaluate to true at that point in code execution. Assertions can help a programmer read the code, help a compiler compile it, or help the program detect its own defects.


For the latter, some programs check assertions by actually evaluating the predicate as they run. Then, if it is not in fact true – an assertion failure –, the program considers itself to be broken and typically deliberately crashes or throws an assertion failure exception.

The official Python documentation for assert can be found here:

https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

assert is in fact not a function, but a statement. It is a check that a certain condition holds. If not, the program will fail to run in some way. In the Python case, an AssertionError will be raised:

if __debug__:
if not expression: raise AssertionError

More specifically, the assertion in your question will fail if Python can not be found in the title of the http://www.python.org page.

Using assert in for loop

assert will raise an exception (AssertionError) if the condition is not met. If an exception is raised, it halts the current control flow and raises until it's caught (or until the program terminates). Typically you use an assert to indicate something that has gone unexpectedly wrong such that your program should immediately terminate.

What I think you want to do is use a simple if statement:

import logging

with open('checkpoints-results.log') as file:
for row in file:
if '"status":"Unresolved"' in row:
logging.warning(row)
continue
# do other stuff with the row?

Example use of assert in Python?

A good guideline is using assert when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an assert. This assert failing means your assumption isn't correct, which means your code isn't correct.



Related Topics



Leave a reply



Submit