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

Chris Angelico rosuav at gmail.com
Sat Mar 12 07:10:07 EST 2016


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.

ChrisA



More information about the Python-list mailing list