본문 바로가기
Python/Python FAQ

Python 내 타입 힌트에서 함수 타입을 어떻게 지정할 수 있을까요?, How can I specify the function type in my type hints?

by 베타코드 2023. 10. 8.
반응형

질문


변수의 타입 힌트를 함수 타입으로 지정하는 방법은 어떻게 되나요? typing.Function은 없고, 관련된 PEP인 PEP 483에도 그에 대한 내용을 찾을 수 없었습니다.


답변


As @jonrsharpe noted in a comment, this can be done with typing.Callable:

from typing import Callable

def my_function(func: Callable):

Note: Callable on its own is equivalent to Callable[..., Any]. Such a Callable takes any number and type of arguments (...) and returns a value of any type (Any). If this is too unconstrained, one may also specify the types of the input argument list and return type.

For example, given:

def sum(a: int, b: int) -> int: return a+b

The corresponding annotation is:

Callable[[int, int], int]

That is, the parameters are sub-scripted in the outer subscription with the return type as the second element in the outer subscription. In general:

Callable[[ParamType1, ParamType2, ..., ParamTypeN], ReturnType]
반응형

댓글