python中是否有内置的标识函数? [英] Is there a builtin identity function in python?
问题描述
我想指出一个什么都不做的函数:
def identity(*args)返回参数
我的用例是这样的
尝试:gettext.find(...)..._ = gettext.gettext别的:_ = 身份
当然,我可以使用上面定义的 identity
,但是内置的肯定会运行得更快(并避免我自己引入的错误).
显然,map
和 filter
使用 None
作为标识,但这特定于它们的实现.
做了更多的研究,没有,在 issue 1673203 来自 Raymond Hettinger 说不会有:
<块引用>最好让人们编写自己的琐碎传递并考虑签名和时间成本.
所以实际上更好的方法是(lambda 避免命名函数):
_ = lambda *args: args
- 优点:接受任意数量的参数
- 缺点:结果是参数的盒装版本
或
_ = lambda x: x
- 优点:不改变参数的类型
- 缺点:只需要 1 个位置参数
I'd like to point to a function that does nothing:
def identity(*args)
return args
my use case is something like this
try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity
Of course, I could use the identity
defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).
Apparently, map
and filter
use None
for the identity, but this is specific to their implementations.
>>> _=None
>>> _("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Doing some more research, there is none, a feature was asked in issue 1673203 And from Raymond Hettinger said there won't be:
Better to let people write their own trivial pass-throughs and think about the signature and time costs.
So a better way to do it is actually (a lambda avoids naming the function):
_ = lambda *args: args
- advantage: takes any number of parameters
- disadvantage: the result is a boxed version of the parameters
OR
_ = lambda x: x
- advantage: doesn't change the type of the parameter
- disadvantage: takes exactly 1 positional parameter
这篇关于python中是否有内置的标识函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!