On 27 May 2021, at 17:24, Steven D'Aprano
wrote: On Thu, May 27, 2021 at 04:37:10PM +0200, Ronald Oussoren wrote:
One common use for function defaults is to optimize function lookups to local variables instead of global or builtins:
def func(arg, len=len): # now len is a fast local lookup instead of a slow name lookup
That’s a CPython performance hack,
No it isn't. I think we can assume than any non-crappy implementation will have faster access to locals than globals and builtins, or at least no worse. So it is a fair expectation that any time you can turn a global lookup into a local lookup, you should have some performance benefit.
It is a performance hack regardless. There are other solutions possible, including bytecode rewriting (look for “Binding Constants at Compile Time” in the Python Cookbook. That particular implementation likely doesn’t work anymore due to changes in the bytecode representation, but the general idea is still valid (and I’ve used it in the past because it leads to somewhat cleaner code). This could even be an opt-in language feature (“from __future__ import no_builtins_override”, or a better thought out alternative). That said, we’re sailing off-topic. There should be much more enticing reasons for having this “static” feature than “rebinding globals as locals” before anyone will consider adding it to the language. Ronald — Twitter / micro.blog: @ronaldoussoren Blog: https://blog.ronaldoussoren.net/