What does Python itertools `constant_factory` look like superior to` lambda: x`?

defaultdict documentation defaultdict an example:

 >>> def constant_factory(value): ... return itertools.repeat(value).next 

as "a faster and more flexible way to create persistent functions."

How does it surpass

 def constant_factory(value): return lambda : value 

?

Note that, of course, no one would define a function for this ... just using (lambda: 42) becomes clearer and shorter than calling constant_factory(42) .

To create a factory constant that returns mutable, if necessary, you can use (lambda x=[]:x) (btw is something to do constant_factory([]) , but it's something that often bites back ... see for example this question ).

+6
source share
1 answer

Surprisingly, using itertools.repeat(value).next is actually about 30% two to three times faster in Python 2 and Python 3 (with an obvious change to __next__ ).

This is not much, but also no reason to spend it.

PS: I would say that this shows that lambda can be improved (I see no logical reason to have a related method faster than a closure), but lambda not very popular in the Python community. Strike>

The reason for this is that itertools primitives itertools implemented in C, and lambda executes Python bytecode. Just returning the captured value is very fast, but nonetheless, it is still bytecode and requires a lot of tweaking / breaking like any Python function call.

+4
source

Source: https://habr.com/ru/post/979800/


All Articles