본문 바로가기

개발

파이썬에서 arguments로 *(별표)만 쓴 경우!?

반응형

fastapi의 코드를 보던 중 함수의 arguments*만을 쓴 것을 발견했다. 난생 처음 본 표현법이라서 직접 테스트 해보며 뭔지 알아냈다.

...(생략)

def get_param_sub_dependant(
    *, param: inspect.Parameter, path: str, security_scopes: List[str] = None
) -> Dependant:  # param앞에 *를 쓴 것이 보이는가?
    depends: params.Depends = param.default
    if depends.dependency:
        dependency = depends.dependency
    else:
        dependency = param.annotation
    return get_sub_dependant(
        depends=depends,
        dependency=dependency,
        path=path,
        name=param.name,
        security_scopes=security_scopes,
    )

...(생략)

기본적으로 python의 함수의 arguments로는 positinal argumentskeyword arguments가 존재한다.
예를들어, 아래와 같은 함수가 존재한다고 가정해보자.

def tell(sender, recipient, what):
    print(f"{sender} told {what} to {recipient}.")

이렇게 함수를 만들면, positional arguements와 keyword arguments를 조합해서 아래와 같이 사용할 수 있다.

# positional arguments만 사용한 경우
tell("SJ", "her", "something")

# keyword arguments만 사용한 경우
tell(sender="SJ", recipient="her", what="something")

# positional arguments와 keyword arguments를 조합한 경우
tell("SJ", "her", what="something")
tell("SJ", recipient="her", what="seomthing")
>>
SJ told something to her.
SJ told something to her.
SJ told something to her.
SJ told seomthing to her.

단, keyword arguments를 positional arguments보다 먼저 사용하면 SyntaxError가 발생한다.

tell(sender="SJ", "her", "something")
>> SyntaxError: positional argument follows keyword argument

*를 사용하면 *이후의 arguments들을 keyword arguments로 강제할 수 있다. 예를들어 아래와 같이 정의한 경우에는 recipient와 what을 positional arguments로 사용할 수 없다. 사용할 경우 TypeError가 발생한다.

def tell(sender, *, recipient, what):
    print(f"{sender} told {what} to {recipient}.")

tell("SJ", "her", "something")
>> TypeError: tell() takes 1 positional argument but 3 were given

아래와 같이 사용하여야 작동한다.

tell("SJ", recipient="her", what="something")
>> SJ told something to her.

아무래도 keyword arguments를 쓰는 것이 코드를 읽는 사람 입장에서 함수를 이해하기가 훨씬 쉽기 때문에, 이런식으로 강제하는 것도 가독성이나 실수 예방측면에서 좋을 것 같다.

반응형