0

Is there any built-in stub function that returns the same object it was given? I'm looking for a shortcut to lambda x: x (like operator.itemgetter(1) is a shortcut and more efficient way of saying lambda x: x[1]).

I technically wish for the boolean value, but timeit showed that lambda x: x was faster than bool() (probably because bool creates a new object) by 10%, and since it's being defined a few times but called many more, it makes a difference.
I only use the variable for if statements so I don't care whether it returns True or the value itself and tested using __bool__.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • I'm not sure what you want, but why do you need an identity function when you already have the variable that it will return? – OneCricketeer Mar 27 '16 at 09:34
  • @cricket_007 it's being used as a fill function for validation. On some objects the validation is smart, on others it's just the truth value. – Bharel Mar 27 '16 at 09:37
  • I think `lambda x: x` is the usual way. – wRAR Mar 27 '16 at 09:38
  • @wRAR it is **a** way, not sure if the usual. It's the same reason `operator.itemgetter` exists. You don't need it but it's more efficient and understandable. – Bharel Mar 27 '16 at 09:41
  • I agree with wRAR on the `lambda`, but you might also consider the [`copy`](https://docs.python.org/3.4/library/copy.html) module? While creating a copy of `x` (if that's acceptable) it seems good enough for your purpose. – Jens Mar 27 '16 at 09:44
  • @Bharel sure, I mean I didn't see anything better – wRAR Mar 27 '16 at 09:46
  • @wRAR no problem, it's just that I'm defining it repeatedly and using it even more so if there is a shortcut which proves to be even 5% faster and more readable as an added bonus, it'll be of great use. – Bharel Mar 27 '16 at 09:50
  • @Bharel `lambda obj: obj` is the idiomatic way - it was discussed and rejected as potentially going into the standard lib in 2009 - see: https://mail.python.org/pipermail/python-ideas/2009-March/003647.html – Jon Clements Mar 27 '16 at 09:52
  • @Jens creating a copy of x will be much slower I believe. – Bharel Mar 27 '16 at 09:53

0 Answers0