Assertions

Chris Angelico rosuav at gmail.com
Thu Sep 21 14:08:19 EDT 2017


On Fri, Sep 22, 2017 at 3:49 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Fri, 22 Sep 2017 03:31 am, Chris Angelico wrote:
>
>> Impressive. That means that, in 2.7, it's actually equivalent to:
>>
>>>>> def test3():
>> ...     if not foo: raise AssertionError, "bar baz"
>
> That's nothing. In 1.5 (yes, *one* point five) it's equivalent to something more
> or less like this:
>
> def test4():
>     if __debug__:
>         if foo:
>             return
>         raise AssertionError('bar baz')

AIUI, it's still equivalent to that - with the proviso that the
optimizer removes references to __debug__:

>>> def foo():
...   if __debug__: print("Debugging")
...
>>> import dis
>>> dis.dis(foo)
  2           0 LOAD_CONST               1 ('Debugging')
              3 PRINT_ITEM
              4 PRINT_NEWLINE
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE

and the optimizer may or may not differentiate between the two ways of
writing the code. It is interesting to observe the changes to the
optimizer, but none of them are assert-specific.

(And I just made an assertion about the optimizer and the assert
statement. It is falsifiable, but if true, it is an optimal
optimizer/assertion assertion.)

>> 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
>
> Now that you've showed me yours, I suppose I have to show you mine.
>
> Python 2.7.2 (default, May 18 2012, 18:25:10)
>
> So definitely version dependent.

Yep! Apparently five years of patchlevel changes can include some that
make notable byte-code changes. Which doesn't surprise me, merely
amuses.

ChrisA



More information about the Python-list mailing list