0

When calling a function that expects a function as parameter, sometimes I just want to return the identity function lambda x:x. This seems inefficient, since it needs a function call to just return x. Is there a more efficient built-in for that?

Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
  • 1
    So... you want the identity function, but not a function call? – Sören Mar 15 '22 at 19:54
  • @Sören yes, I want to save the function call. Since in my use-case, this function is going to be called millions of times. – Erel Segal-Halevi Mar 15 '22 at 19:54
  • 2
    How can you save a function call of a function argument? Can you provide a [mre] to help demonstrate the issue? – Tomerikoo Mar 15 '22 at 19:56
  • 1
    Also, do you actually have proof that this is your bottleneck? *"Is there a more efficient"* - I doubt that calling `lambda x:x` is the cause for any efficiency problems... – Tomerikoo Mar 15 '22 at 19:57
  • 3
    Did you profile your script and determine that that was the bottleneck? If it's just a hunch, then don't bother; get hard numbers before you start optimizing anything (otherwise it's [premature optimization](https://softwareengineering.stackexchange.com/a/80092)). Also, [here](https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script) is a post about how to profile Python scripts. – Random Davis Mar 15 '22 at 19:59
  • If it's being called millions of times, you have a problem. What's going on here? – Mous Mar 15 '22 at 20:26
  • 1
    FWIW, calling a generic identity function a million times took less than a tenth of a second, 0.07 s – juanpa.arrivillaga Mar 15 '22 at 20:46
  • Anyway, I don't really see how a built-in function would take away the need for a function call. The python function itself will basically be two OP codes, a LOAD_FAST and a RETURN_VALUE. I suppose a function written in C that just returns the PyObject pointer would be faster, but if you are optimizing at this level, CPython probably isn't the language / implementation for you – juanpa.arrivillaga Mar 15 '22 at 20:48

0 Answers0