IT박스

파이썬에 내장 기능이 있습니까?

itboxs 2020. 7. 1. 08:18
반응형

파이썬에 내장 기능이 있습니까?


아무것도하지 않는 함수를 가리키고 싶습니다.

def identity(*args)
    return args

내 유스 케이스는 다음과 같습니다

try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity

물론 identity정의를 사용할 수는 있지만 내장 기능이 더 빠르게 실행됩니다 (내 버그로 인한 버그를 피할 수 있음).

분명히, map그리고 정체성을 위해 filter사용 None하지만, 이것은 그들의 구현에 따라 다릅니다.

>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

더 많은 연구를 수행 한 결과 1673203 에 기능이 요청 되지 않았 으며 Raymond Hettinger는 다음과 같은 내용은 없다고 말했습니다 .

사람들이 자신의 사소한 패스 스루를 작성하고 서명 및 시간 비용에 대해 생각하게하는 것이 좋습니다.

그래서 그것을하는 더 좋은 방법은 실제로 (람다는 함수의 이름을 피하는 것입니다) :

_ = lambda *args: args
  • 장점 : 여러 매개 변수를 사용합니다
  • 단점 : 결과는 박스 버전의 매개 변수입니다.

또는

_ = lambda x: x
  • 장점 : 매개 변수의 유형을 변경하지 않습니다
  • 단점 : 정확히 1 개의 위치 매개 변수를 사용함

https://en.wikipedia.org/wiki/Identity_function에 정의 된대로 identity 함수 는 단일 인수를 사용하여 변경되지 않은 상태로 반환합니다.

def identity(x):
    return x

서명을 원할 때 요구하는 def identity(*args)것은 여러 인수를 취하기를 원하기 때문에 엄격하게 ID 함수 아닙니다 . 괜찮습니다.하지만 파이썬 함수는 여러 결과를 반환하지 않으므로 문제가 발생하므로 모든 인수를 하나의 반환 값으로 구성하는 방법을 찾아야합니다.

파이썬에서 "다중 값"을 반환하는 일반적인 방법은 기술적으로 하나의 반환 값이지만 여러 값인 것처럼 대부분의 컨텍스트에서 사용할 수있는 값의 튜플을 반환하는 것입니다. 하지만 여기서하는 것은

>>> def mv_identity(*args):
...     return args
...
>>> mv_identity(1,2,3)
(1, 2, 3)
>>> # So far, so good. But what happens now with single arguments?
>>> mv_identity(1)
(1,)

그리고 고정 여기에 다양한 대답이 표시대로 신속하게 문제 것은 다른 문제를 제공합니다.

따라서 요약하면 파이썬에는 다음과 같은 이유로 식별 함수가 정의되어 있지 않습니다.

  1. 공식적인 정의 (단일 인수 함수)는 그다지 유용하지 않으며 작성하기가 쉽지 않습니다.
  2. 정의를 여러 인수로 확장하는 것은 일반적으로 잘 정의되어 있지 않으므로 특정 상황에 필요한 방식으로 작동하는 고유 버전을 정의하는 것이 훨씬 좋습니다.

정확한 경우를 위해

def dummy_gettext(message):
    return message

거의 확실하게 원하는 것입니다-호출 규칙이 동일하고을 반환 gettext.gettext하는 함수는 인수를 변경하지 않고 반환하며 함수의 역할과 용도를 명확하게 지정합니다. 성능이 중요한 고려 사항이라면 충격을받을 것입니다.


당신은 잘 작동합니다. 매개 변수 수가 수정되면 다음과 같은 익명 함수를 사용할 수 있습니다.

lambda x: x

아닙니다.

당신의 identity:

  1. lambda * args : args와 같습니다.
  2. 그것의 인수를 윌 박스-즉

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

따라서 lambda arg: arg진정한 아이덴티티 기능을 원한다면 사용할 수 있습니다.

주의 :이 예제는 내장 id함수를 사용하지 않을 것입니다 (아마도 사용하지 않을 것입니다).


There is no a built-in identity function in Python. An imitation of the Haskell's id function would be:

identity = lambda x, *args: (x,) + args if args else x

Example usage:

identity(1)
1
identity(1,2)
(1, 2)

Since identity does nothing except returning the given arguments, I do not think that it is slower than a native implementation would be. It might even be faster, because it saves a call to a native function.


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.


The thread is pretty old. But still wanted to post this.

It is possible to build an identity method for both arguments and objects. In the example below, ObjOut is an identity for ObjIn. All other examples above haven't dealt with dict **kwargs.

class test(object):
    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
    def identity (self):
        return self

objIn=test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n')
objOut=objIn.identity()
print('args=',objOut.args,'kwargs=',objOut.kwargs)

#If you want just the arguments to be printed...
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().args)
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().kwargs)

$ py test.py
args= ('arg-1', 'arg-2', 'arg-3', 'arg-n') kwargs= {'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}
('arg-1', 'arg-2', 'arg-3', 'arg-n')
{'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}

참고URL : https://stackoverflow.com/questions/8748036/is-there-a-builtin-identity-function-in-python

반응형