[Python-ideas] Make Python code read-only

Victor Stinner victor.stinner at gmail.com
Wed May 21 02:09:03 CEST 2014


2014-05-21 0:44 GMT+02:00 Greg Ewing <greg.ewing at canterbury.ac.nz>:
>> Optimizations possible when the code is read-only
>> =================================================
>>
>> * Inline calls to functions.
>>
>> * Replace calls to pure functions (without side effect) with the
>> result. For example, len("abc") can be replaced with 3.
>
> I'm skeptical about how much difference this would make.
> In most of the Python code I've seen, calls to module-level
> functions are relatively rare -- most calls are method
> calls.

If the class is read-only and has a __slots__ class attribute, methods
cannot be modified anymore. If you are able to get (compute) the type
of an object, you can optimize the call to the method.

Dummy example:
---
chars=[]
for ch in range(32, 126):
    chars.append(chr(ch))
print(''.join(chars))
---

Here you can guess that the type of chars in "chars.append" is list.
The list.append() method is well known (and it is read-only, even if
my global read-only mode is disabled, because list.append is a builtin
type).

You may inline the call in the body of the loop. Or you can at least
move the lookup of the append method out of the loop.

Victor


More information about the Python-ideas mailing list