블로그 이미지
Peter Note
AI & Web FullStacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2024. 8. 4. 15:12 LLM FullStacker/Python

Google 스타일 docstring의 전체 포맷을 설명하기 위해, 모든 주요 섹션을 포함한 예시를 제공합니다. 이 예시는 함수와 클래스에 대한 포맷을 모두 다룹니다.

함수의 예시

def embed_query(text, model='default', verbose=False):
    """
    Embed query text using a specified model.

    This function takes a text string and converts it into an embedding
    using the specified model. It supports different models for embedding
    and can provide verbose output.

    Args:
        text (str): The text to embed. This should be a plain string without any special formatting.
        model (str, optional): The model to use for embedding. Defaults to 'default'.
        verbose (bool, optional): If True, the function will print detailed information during execution. Defaults to False.

    Returns:
        list: A list representing the text embedding.

    Raises:
        ValueError: If the text is empty or the model is not supported.
        RuntimeError: If the embedding process fails.

    Examples:
        >>> embed_query("Hello, world!")
        [0.1, 0.3, 0.5, ...]
        >>> embed_query("Hello, world!", model='advanced')
        [0.2, 0.4, 0.6, ...]

    Notes:
        The embedding process can take a significant amount of time
        depending on the length of the text and the complexity of the model.
    """
    if not text:
        raise ValueError("Text cannot be empty.")
    if model not in ['default', 'advanced']:
        raise ValueError("Unsupported model.")
    # Implementation of embedding process...
    embedding = [0.1, 0.3, 0.5]  # Dummy embedding
    if verbose:
        print(f"Embedding for '{text}' generated using model '{model}'.")
    return embedding

클래스의 예시

class EmbeddingModel:
    """
    A model for generating embeddings from text.

    This class provides methods to embed text using various models. It can
    handle different types of text inputs and supports multiple embedding
    techniques.

    Attributes:
        model_name (str): The name of the model.
        version (str): The version of the model.
        is_trained (bool): Indicates whether the model has been trained.

    Methods:
        train(data):
            Trains the model using the provided data.
        embed(text):
            Embeds the given text and returns the embedding.
        save(path):
            Saves the model to the specified path.
    """

    def __init__(self, model_name, version):
        """
        Initializes the EmbeddingModel with a name and version.

        Args:
            model_name (str): The name of the model.
            version (str): The version of the model.
        """
        self.model_name = model_name
        self.version = version
        self.is_trained = False

    def train(self, data):
        """
        Trains the model using the provided data.

        This method takes a dataset and trains the embedding model.
        It updates the is_trained attribute to True upon successful training.

        Args:
            data (list): A list of training data samples.

        Returns:
            None

        Raises:
            ValueError: If the data is empty or not in the expected format.

        Examples:
            >>> model = EmbeddingModel('text_model', '1.0')
            >>> model.train(['sample1', 'sample2'])
        """
        if not data:
            raise ValueError("Training data cannot be empty.")
        # Implementation of training process...
        self.is_trained = True

    def embed(self, text):
        """
        Embeds the given text and returns the embedding.

        Args:
            text (str): The text to embed.

        Returns:
            list: A list representing the text embedding.

        Raises:
            RuntimeError: If the model has not been trained.

        Examples:
            >>> model = EmbeddingModel('text_model', '1.0')
            >>> model.train(['sample1', 'sample2'])
            >>> model.embed('Hello, world!')
            [0.1, 0.3, 0.5, ...]
        """
        if not self.is_trained:
            raise RuntimeError("Model must be trained before embedding.")
        # Implementation of embedding process...
        return [0.1, 0.3, 0.5]  # Dummy embedding

    def save(self, path):
        """
        Saves the model to the specified path.

        Args:
            path (str): The file path to save the model to.

        Returns:
            None

        Examples:
            >>> model = EmbeddingModel('text_model', '1.0')
            >>> model.save('/path/to/save/model')
        """
        # Implementation of save process...
        pass

주요 구성 요소

  1. 요약 설명(Summary):
    • 클래스나 함수의 첫 번째 줄에서 기능을 간략하게 설명합니다.
    • 간결하고 명확하게 작성하며, 마침표로 끝냅니다.
  2. 확장 설명(Extended Description):
    • 요약 설명 이후 빈 줄을 두고, 기능에 대한 상세 설명을 작성합니다.
    • 설명이 길어질 경우 여러 문단으로 나눌 수 있습니다.
  3. Args (인수):
    • Args: 섹션에서 함수나 메소드의 매개변수를 설명합니다.
    • 각 매개변수에 대해 이름, 유형, 설명을 포함합니다.
    • 선택적 매개변수는 (optional)로 표시합니다.
  4. Attributes (속성):
    • 클래스의 속성을 설명합니다.
    • 각 속성의 이름과 설명을 포함합니다.
  5. Methods (메소드):
    • 클래스의 메소드를 설명합니다.
    • 각 메소드의 이름과 기능을 간략하게 설명합니다.
  6. Returns (반환값):
    • 함수나 메소드의 반환값을 설명합니다.
    • 반환값의 유형과 설명을 포함합니다.
    • 반환값이 없으면 생략할 수 있습니다.
  7. Raises (예외):
    • 함수나 메소드가 발생시킬 수 있는 예외를 설명합니다.
    • 예외의 유형과 설명을 포함합니다.
  8. Examples (예제):
    • 함수나 메소드의 사용 예제를 포함합니다.
    • 코드 블록을 사용하여 예제를 보여줍니다.
  9. Notes (참고):
    • 함수나 메소드에 대한 추가적인 참고 사항을 작성합니다.
    • 필요한 경우에만 포함합니다.

이러한 구성 요소들을 사용하면, Google 스타일의 docstring을 통해 코드의 문서화를 일관성 있게 작성할 수 있습니다.

posted by Peter Note