How to use an assert statement for debug with an example

All new tutorial are submitted here.
They will be moved to the main Tutorials section once they have been approved by mods and admins.

How to use an assert statement for debug with an example

Postby akD » Mon Apr 25, 2016 10:04 am

An Assert is used to check the valid condition or logic of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.
An assert help to give smooth exit of project in case of any failure if used in project appropriately.

The simple form of, assert expression, is equivalent to


Code: Select all
if __debug__:
   if not expression: raise AssertionError


The extended form of , assert expression1, expression2, is equivalent to

Code: Select all
if __debug__:
   if not expression1: raise AssertionError(expression2)


Example 1:


Code: Select all
#!/usr/bin/python

str = 'hello Pyhton!'
strNull = 'string is Null'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)



Code: Select all
[b]Output:[/b]
hello Pyhton!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py
Package ...................... None


Example 2:


Code: Select all
#!/usr/bin/python

str = ''
strNull = 'NULL String'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)



------------------------------------------------------

Output:

AssertionError: NULL String
ERROR: Module: hello could not be imported
Last edited by Yoriz on Mon Apr 25, 2016 11:48 am, edited 1 time in total.
Reason: First post lock.
akD
 
Posts: 1
Joined: Mon Apr 25, 2016 9:33 am

Re: How to use an assert statement for debug with an example

Postby micseydel » Mon Apr 25, 2016 11:10 pm

Why the quote tags?
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
micseydel
 
Posts: 3000
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to Tutorial Submissions

Who is online

Users browsing this forum: No registered users and 3 guests