Tuple parameter unpacking in 3.x

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Oct 5 02:16:50 CEST 2008


On Sat, 04 Oct 2008 17:07:14 +0200, Martin Geisler wrote:

> A somewhat related question: do I pay a performance penalty when I let a
> function define an inner function like this:
> 
>   def foo():
> 
>     def bar()
>       ...
> 
>     bar()
> 
> compared to just defining it once outside:
> 
>   def bar():
>     ...
> 
>   def foo():
>     ...
>     bar()
> 
> I'm thinking that each execution of the first foo could spend a little
> time defining a new bar each time, or is that not how things work?
> 
> I realize that defining bar as an inner function has the advantage of
> being able to see variables in the namespace of foo.

That is the main advantage, followed by reducing namespace pollution, but 
yes there is a very small performance penalty.


>>> def outer(x):
...     return x+1
...
>>> def func(x):
...     return outer(x+1)
...
>>>
>>> def func2(x):
...     def inner(x):
...             return x+1
...     return inner(x+1)
...
>>> assert func(37) == func2(37)
>>> from timeit import Timer
>>> t1 = Timer('func(23)', 'from __main__ import func')
>>> t2 = Timer('func2(23)', 'from __main__ import func2')
>>> t1.repeat()
[1.5711719989776611, 0.82663798332214355, 0.82708191871643066]
>>> t2.repeat()
[1.8273210525512695, 1.1913230419158936, 1.1786220073699951]



-- 
Steven



More information about the Python-list mailing list