본문으로 바로가기
반응형


Returning more than one variable type from function call

만약 함수가 list, tuple, dictionary등의 타입을 리턴한다면 함수를 호출하는 쪽에서는 항상 리턴값의 타입을 검사해야한다.

이것은 코드의 복잡성을 증가시키는 일이다.

따라서 호출하는 쪽에서 타입을 검사하는 방법보다는 함수에서 값을 리턴할 때 raise를 통해 오류를 발생시켜주는 것이 낫다.


Anti-pattern

def get_secret_code(password):
    if password != "bicycle":
        return None
    else:
        return "42"

secret_code = get_secret_code("unicycle")

if secret_code is None:
    print("Wrong password.")
else:
    print("The secret code is {}".format(secret_code))

위 코드를 보자. get_secret_code()는 호출하는 쪽에서 정확한 패스워드가 입력됐는지 검사하고 특정한 값들을 반환한다.

패스워드가 일치하지 않는다면 None을 반환한다.

이러한 부분은 호출하는 부분에서 타입을 검사해야하기 때문에 코드를 유지보수하기 힘들게 만든다.


Best practice

def get_secret_code(password):
    if password != "bicycle":
        raise ValueError
    else:
        return "42"

try:
    secret_code = get_secret_code("unicycle")
    print("The secret code is {}".format(secret_code))
except ValueError:
    print("Wrong password.")

따라서 위와 같은 형태로 코드를 수정해야한다.

한마디로 특정 조건에 만족하지 않는다면 예외를 raise시키는 방법이다.

부적절한 입력값이 들어오거나 조건에 만족하지 않는 값이 들어온다면 함수는 아무런 값도 리턴하지 않을 것이다.

대신에 함수쪽에서 예외를 발생시킨다.


출처 : https://docs.quantifiedcode.com/python-anti-patterns/maintainability/returning_more_than_one_variable_type_from_function_call.html

반응형