Assertion in list comprehension

beginner zyzhu2000 at gmail.com
Wed Aug 1 17:37:23 CEST 2007


Hi,

Does anyone know how to put an assertion in list comprehension? I have
the following list comprehension, but I want to use an assertion to
check the contents of rec_stdl. I ended up using another loop which
essentially duplicates the functions of list comprehension. It just
look like a waste of coding and computer time to me.

I just wish I could put the assertions into list comprehensions.

        x=[(rec_stdl[0].st/10000.0,
            rec_stdl[0].cl,
            rec_stdl[0].bb,
            rec_stdl[0].bo,
            rec_stdl[1].bb,
            rec_stdl[1].bo,
            rec_stdl[0].ex
           )
           for rec_stdl in rec_by_ex if len(rec_stdl)==2
        ]

        #duplicated loop
        if __debug__:
            for rec_stdl in rec_by_ex:
                l=len(rec_stdl)
                assert(l<=2 and l>0)
                if l==2:
                    assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P")
                    assert(rec_stdl[0].ex==rec_stdl[1].ex)
                    assert(rec_stdl[0].st==rec_stdl[1].st)
                    assert(rec_stdl[0].cp==rec_stdl[1].cp)

Thanks,
Geoffrey




More information about the Python-list mailing list