Static variables [was Re: syntax difference]

Steven D'Aprano steven.d'aprano at 1
Sun Jun 24 11:51:54 EDT 2018


From: Steven D'Aprano <steve+comp.lang.python at pearwood.info>

On Sun, 24 Jun 2018 11:23:12 +0100, Bart wrote:

> On 24/06/2018 01:53, Ben Bacarisse wrote:
>> Bart <bc at freeuk.com> writes:
>
>>> Wow. (Just think of all the times you write a function containing a
>>> neat bunch of local functions, every time it's called it has to create
>>> a new function instances for each of those functions, even if they are
>>> not used.)
>>
>> I am surprised that this surprises you, and equally surprised that you
>> seem to think it's going to be in some way grossly inefficient.
>
> Steven D'Aprano's reply suggests there /is/ some inefficiency which is
> why [according to him] nested functions are rarely used that way.

Building functions is cheap. Cheap is not free.

Inner functions that aren't exposed to the outside cannot be tested in
isolation, you can't access them through help() interactively. Given the choice
 between:


# can't test eggs, can't re-use it
def func():
    def eggs():
        ...
    ...

and:

# can test it, can re-use it
def _eggs():
    ...

def func():
    ...


most people go for the later simply because it is better development practice.
The very small performance penalty hardly comes into it.

For what its worth, the cost of assembling a basic function is comparable to
creating an empty dict:

[steve at ando ~]$ python3.5 -m timeit "lambda: None" 10000000 loops, best of 3:
0.195 usec per loop [steve at ando ~]$ python3.5 -m timeit "{}" 1000000 loops,
best of 3: 0.212 usec per loop


so not expensive, but not free either. If using an inner function has no
advantages to you, why pay that tiny cost for no benefit?


--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing it everywhere."
 -- Jon Ronson

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)



More information about the Python-list mailing list