Global VS Local Subroutines

Eryk Sun eryksun at gmail.com
Thu Feb 10 14:39:49 EST 2022


On 2/10/22, BlindAnagram <blindanagram at nowhere.org> wrote:
>
> This is exactly what I felt too but I then wondered if the code was
> recreated dynamically or was static with just a reference being created
> on each invocation of the parent.  The overhead in this case would be
> negligible. But then I thought 'what about the context for the inner
> function invocation' - maybe its not as simple as this!  Oh dear, I need
> to understand Python's internals.

The bytecode for a() is a constant in b(). But the function object
itself isn't cached. Each time b() is called, a new function object
a() has to be created, with its defaults, keyword-only defaults, and
closure. The more complicated the latter are, the more work is
involved. Generally, however, the time to create a() will be an
insignificant fraction of the execution time of b(). If the latter
isn't the case, the cost only accumulates to something significant if
b() is called in a tight loop for an extended period.


More information about the Python-list mailing list