Is there a builtin identity function in python?

后端 未结 8 1843
情书的邮戳
情书的邮戳 2020-11-28 07:37

I\'d like to point to a function that does nothing:

def identity(*args)
    return args

my use case is something like this

         


        
相关标签:
8条回答
  • 2020-11-28 08:33

    Stub of a single-argument function

    gettext.gettext (the OP's example use case) accepts a single argument, message. If one needs a stub for it, there's no reason to return [message] instead of message (def identity(*args): return args). Thus both

    _ = lambda message: message
    
    def _(message):
        return message
    

    fit perfectly.

    ...but a built-in would certainly run faster (and avoid bugs introduced by my own).

    Bugs in such a trivial case are barely relevant. For an argument of predefined type, say str, we can use str() itself as an identity function (because of string interning it even retains object identity, see id note below) and compare its performance with the lambda solution:

    $ python3 -m timeit -s "f = lambda m: m" "f('foo')"
    10000000 loops, best of 3: 0.0852 usec per loop
    $ python3 -m timeit "str('foo')"
    10000000 loops, best of 3: 0.107 usec per loop
    

    A micro-optimisation is possible. For example, the following Cython code:

    test.pyx

    cpdef str f(str message):
        return message
    

    Then:

    $ pip install runcython3
    $ makecython3 test.pyx
    $ python3 -m timeit -s "from test import f" "f('foo')"
    10000000 loops, best of 3: 0.0317 usec per loop
    

    Build-in object identity function

    Don't confuse an identity function with the id built-in function which returns the 'identity' of an object (meaning a unique identifier for that particular object rather than that object's value, as compared with == operator), its memory address in CPython.

    0 讨论(0)
  • 2020-11-28 08:34

    No, there isn't.

    Note that your identity:

    1. is equivalent to lambda *args: args
    2. Will box its args - i.e.

      In [6]: id = lambda *args: args
      
      In [7]: id(3)
      Out[7]: (3,)
      

    So, you may want to use lambda arg: arg if you want a true identity function.

    NB: This example will shadow the built-in id function (which you will probably never use).

    0 讨论(0)
提交回复
热议问题