#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12

    Assert statement


    Hi,
    Wanted to know abt the assert statement....

    Suppose I've some code like this...

    Code:
    assert (id(a)!= id(b))
    can anyone explain this to me? I read the documentation...but not much is explained!!

    Thanks & Rgds,
    Subha
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    An assertion in Python is very like an exception.

    It is a quick way for a program to raise the flag that what you thought should be true is not. It is often used in pre-release code to check the algorithm you are using has predictable behaviour.
    Code:
    try:
        assert ( 1== 0 )
    except AssertionError:
        print "assertion raised 1 is not equal to 0 !!"
    grimey
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Ok thanks Grimey got it!
    This means for my example....

    Code:
    assert (id(a)!= id(b))
    if the address of a and b are the same, then raise an AssertionError....fine thanks!

    Rgds,
    Subha
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Not rocket science , assert is just a conditional raise statement; a shortcut if you want to call it that, so that things like:

    Code:
    if not [/i]expression[/i]: raise Exception, message
    end up something like,
    Code:
    assert expression, message
    i.e.
    Code:
    >>> assert True, 'Damn False!'
    >>> assert False, 'Damn False!'
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AssertionError: Damn False!
    >>>
    As you can see, if the expression evaluates to False, the error is thrown. The only palatable difference is that assert always throws an AssertionError - with raise you can to tell it what type of exception you want to raise i.e. OSError .

    Later ,

    Mark.
    programming language development: www.netytan.com Hula

  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Yes Professor Mark, I got it...you made it very simple!

    Thanks,
    Subha

IMN logo majestic logo threadwatch logo seochat tools logo