Undefined behaviour in C [was Re: The Cost of Dynamism]

Marko Rauhamaa marko at pacujo.net
Sat Mar 26 04:37:55 EDT 2016


Steven D'Aprano <steve at pearwood.info>:

> On Sat, 26 Mar 2016 03:57 am, Marko Rauhamaa wrote:
>> Yes, although the same could be true for Python as well.
>
> Is this a philosophical question? Yes, it *could* be true, in some
> alternate universe, but it isn't actually true.
>
> Python does not have undefined behaviour in the C sense. [...]

>> For example, you could have this program:
>> 
>> ===begin poof.py========================================================
>> assert 1 < 0
>> ===end poof.py==========================================================
>
> The semantics of "assert condition" are equivalent to:
>
> if __debug__:
>     if not condition:
>         raise AssertionError
>
> so assert is intentionally a no-op when Python runs with debug mode disabled
> (the -O command-line switch).

Thing is, some aggressive JITters might make extensive optimization
decisions based on assertions. An assertion is a developers declaration
of certain knowledge. It is there mainly to document design principles
to fellow developers (including the original coder), but since the
assertions have a formal content, the VM could allow itself to rely on
them.

For example,

    def g(n):
        assert type(n) is int
        assert 0 <= n < 256
        return (n + 1) % 256

    def f(n):
        return g(n)**2

The optimizer can optimize f() *knowing* its argument is an unsigned
byte.

Essentially, the JIT would boldly decide that AssertionError is never
raised.

(Although I would hate seeing such assertions routinely sprinkled
everywhere.)

> Anything else would be a bug in the interpreter or compiler.

We'll see what the JITters cook up.


Marko



More information about the Python-list mailing list