Assertions

Chris Angelico rosuav at gmail.com
Thu Sep 21 13:31:50 EDT 2017


On Fri, Sep 22, 2017 at 3:23 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> That is definitely version-dependent, because I've just tried it and got
> different byte-code in Python 2.7.
>
> py> import dis
> py> def test1():
> ...     assert foo, "bar baz"
> ...
> py> def test2():
> ...     if not foo: raise AssertionError("bar baz")
> ...
> py>
> py> dis.dis(test1)
>   2           0 LOAD_GLOBAL              0 (foo)
>               3 POP_JUMP_IF_TRUE        15
>               6 LOAD_GLOBAL              1 (AssertionError)
>               9 LOAD_CONST               1 ('bar baz')
>              12 RAISE_VARARGS            2
>         >>   15 LOAD_CONST               0 (None)
>              18 RETURN_VALUE
> py> dis.dis(test2)
>   2           0 LOAD_GLOBAL              0 (foo)
>               3 POP_JUMP_IF_TRUE        21
>               6 LOAD_GLOBAL              1 (AssertionError)
>               9 LOAD_CONST               1 ('bar baz')
>              12 CALL_FUNCTION            1
>              15 RAISE_VARARGS            1
>              18 JUMP_FORWARD             0 (to 21)
>         >>   21 LOAD_CONST               0 (None)
>              24 RETURN_VALUE

Impressive. That means that, in 2.7, it's actually equivalent to:

>>> def test3():
...     if not foo: raise AssertionError, "bar baz"
...
>>> dis.dis(test3)
  2           0 LOAD_GLOBAL              0 (foo)
              3 POP_JUMP_IF_TRUE        18
              6 LOAD_GLOBAL              1 (AssertionError)
              9 LOAD_CONST               1 ('bar baz')
             12 RAISE_VARARGS            2
             15 JUMP_FORWARD             0 (to 18)
        >>   18 LOAD_CONST               0 (None)
             21 RETURN_VALUE

Although in the 2.7 that I have, the assert statement does actually
*call* AssertionError (ie it constructs an instance and raises it).
What version are you running? Here's mine:

$ python2
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.

ChrisA



More information about the Python-list mailing list