Coding Diary.

(파이썬) def 함수 문서화하기 위한 독스트링(docstring) 쉽게 알아보기 본문

Coding/Python

(파이썬) def 함수 문서화하기 위한 독스트링(docstring) 쉽게 알아보기

life-of-nomad 2024. 6. 11. 10:20
728x90
반응형
지난 글에서 def를 이용하여 함수를 정의하고 호출하는 방법에 대해 알아보았습니다. 이번 글에서는 코드를 더욱 쉽게 이해하고 사용하도록 하기 위한 독스트링(docstring)에 대해 알아보겠습니다.

 

🔻(참고) def 함수🔻

 

(파이썬) def 함수 정의하고 호출하기, 변수 범위

함수를 사용하려면 먼저 함수가 어떤 역할을 하는지, 어떤 입력값이 필요할 수 있는지를 정의해야 합니다. 함수 안에 있는 코드는 우리가 그 함수를 호출하거나 사용할 때만 실행됩니다. 이번

life-of-nomad.tistory.com

 

1. 독스트링(docstring)

  • 함수의 주요 장점 중 하나는 프로그램을 작은 덩어리로 나누는데 도움이 된다는 점입니다.
  • 이렇게 하면 코드의 일부인 함수를 재사용할 수 있으므로 코드를 더 쉽게 작성할 수 있고 읽기도 더 쉽습니다.
  • 함수는 프로세스에 사람이 읽을 수 있는 이름을 부여하기 때문에 코드를 더 읽기 쉽게 만듭니다.
  • 문서 문자열, 또는 독스트링이라는 것은 함수의 목적과 사용 방법을 설명하기 위해 사용하는 유형의 코멘트입니다.
  • 인구 밀도 함수를 예로 들어보겠습니다.
def population_density(population, land_area):
    """ Calculate the population density of an area. """
    return population / land_area
  • 독스트링은 따옴표 3개로 둘러쌓여 있습니다. 
  • 독스트링의 첫 줄은 함수의 목적에 대한 간략한 설명입니다. 문서화가 충분하다고 생각되면 독스트링을 완료하면 됩니다.
  • 함수의 더 긴 설명이 필요하다고 생각되면 정보를 추가할 수 있습니다.
def population_density(population, land_area):
    """Calculate the population density of an area.

    INPUT:
    population: int. The population of that area
    land_area: int or float. This function is unit-agnostic, if you pass in values in terms
    of square km or square miles the function will return a density in those units.

    OUTPUT:
    population_density: population / land_area. The population density of a particular area.
    """
    return population / land_area

 

2. 예시

  • 지난 글에서 정의한 함수 readable_timedelta에 대한 독스트링을 작성해보겠습니다.
def readable_timedelta(days):
    """ Return a string of the number of weeks and days included in days.

    Parameters:
    days -- number of days to convert (int)

    Returns:
    string of the number of weeks and days included in days
    """
    weeks = days // 7
    remainder = days % 7
    return "{} week(s) and {} day()s.".format(weeks, remainder)

 

728x90
반응형