Speed up lookups by using function default args?

I’m sporadically working on what could roughly be called “reducing techincal debt” on a Python project that’s been around for a long time (20 years), and ran into what was an oddity to me… some utility functions that use default arguments that are the same as builtins. That sounds a little odd, so for illustration (this particular paste is fictitious, but real function signatures do contain these two and more):

def foo(obj, isinstance=isinstance, str=str):

Some digging turned up an old tracker issue (13 yrs ago) that claimed a big speedup from “using default arguments to take a snapshot of the global functions and constants used by these functions. This transforms accesses to global variabls into local variable access, i.e. LOAD_FAST instead of LOAD_GLOBAL virtual machine opcodes”.

Is/was this hooey, and if not, is it still valid given a lot of time has passed and we’re fully into a new major Python version?

It’s not hooey, it is real and valid, but of course it depends on the

If the function only calls the builtin once, the benefit is likely to be
negligible. The big benefit is if it occurs in a tight loop.

As with any optimization, don’t guess what will speed the code up,
measure measure measure.

1 Like