The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Chris Angelico rosuav at gmail.com
Sat Mar 12 08:06:34 EST 2016


On Sat, Mar 12, 2016 at 11:28 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 12 Mar 2016 11:10 pm, Chris Angelico wrote:
>
>> On Sat, Mar 12, 2016 at 10:08 PM, BartC <bc at freeuk.com> wrote:
>>>>> You're not mistaken. There are no "character constants" in Python.
>>>>> (Note that the definition would be Unicode codepoints, rather than
>>>>> ASCII values.) I don't often miss them, though.
>>>
>>>> Yes, a complete non-issue.
>>>
>>>
>>> Really? The issue as I see it is this:
>>>
>>> Writing: a=65 generates this byte-code for the right-hand-side:
>>>
>>>     LOAD_CONST      1 (65)       An integer
>>>
>>> But writing instead: a=ord('A') generates this:
>>>
>>>     LOAD_GLOBAL     0 (ord)
>>>     LOAD_CONST      1 ('A')      A string
>>>     CALL_FUNCTION   1
>>
>> I think the "non-issue" here is the difference between ASCII and
>> Unicode. Either way, there's no way to say "the integer with the
>> codepoint of this character" as a literal. But that's actually not
>> even all that necessary, because subscripting a text string yields
>> one-character strings - you almost never need the ordinals.
>>
>> Subscripting a byte string in Py3 yields integers, so you might need
>> ordinals for ASCII byte values. But you can get them the same way:
>>
>>>>> dis.dis(lambda: b"a"[0])
>>   1           0 LOAD_CONST               3 (97)
>>               3 RETURN_VALUE
>>>>> dis.dis(lambda: u"a"[0])
>>   1           0 LOAD_CONST               3 ('a')
>>               3 RETURN_VALUE
>>
>> Whichever one you need, you can get as a compile-time constant.
>
> Chris, what you're looking at is the result of the CPython keyhole optimizer
> doing constant folding. That is **NOT** a language promise. Other
> implementations of Python may lack the keyhole optimizer. Future versions
> may remove it, or allow the user to disable it.
>
> Python the language has no feature that *guarantees* that you can write 'a'
> and get 97 as a compile-time constant.

Very true. However, the peephole optimizer MUST use only what can be
compile-time optimized - unlike a function call. So in terms of
optimizations, it's proof that it's safe.

ChrisA



More information about the Python-list mailing list