Following system colour scheme Selected dark colour scheme Selected light colour scheme

Python 개선 제안 한국어 번역

PEP 424 – 길이 힌트를 노출하는 메서드

Author:
Alex Gaynor <alex.gaynor at gmail.com>
Status:
Final
Type:
Standards Track
Created:
14-Jul-2012
Python-Version:
3.4
Post-History:
15-Jul-2012

Table of Contents

번역·라이선스 안내

이 비공식 한국어 번역은 원문 Copyright 절의 Public Domain 조건에 따라 제공합니다. 원저자와 공식 원문은 그대로 표시합니다. 수정되지 않은 기준 원문 · 공식 최신판

초록

CPython은 현재 여러 이터레이터를 비롯한 여러 타입에 __length_hint__ 메서드를 정의하고 있습니다. 다른 여러 함수(list 등)는 이 메서드를 사용하여 __length_hint__가 반환한 추정치를 바탕으로 리스트의 크기를 미리 정합니다. 크기가 정해져 있지 않아 __len__을 정의하지 않아야 하는 타입(많은 이터레이터 등)은 크기를 추정하거나 계산할 수 있도록 __length_hint__를 정의할 수 있습니다.

명세

이 PEP는 다른 인터프리터와 표준 라이브러리에 속하지 않는 Python 모듈이 구현할 수 있도록 __length_hint__를 공식적으로 문서화합니다.

__length_hint__는 정수(그렇지 않으면 TypeError가 발생합니다) 또는 NotImplemented를 반환해야 하며, 정확할 필요는 없습니다. 컨테이너의 실제 크기보다 크거나 작은 값을 반환해도 됩니다. 반환값이 NotImplemented이면 유한한 길이 추정치가 없다는 뜻입니다. 음수 값은 반환할 수 없습니다(반환하면 ValueError가 발생합니다).

또한 새 함수 operator.length_hint가 추가되며, 이 함수는 다음과 같은 의미를 가집니다(이는 __length_hint__를 어떻게 사용해야 하는지를 정의합니다).:

def length_hint(obj, default=0):
    """Return an estimate of the number of items in obj.

    This is useful for presizing containers when building from an
    iterable.

    If the object supports len(), the result will be
    exact. Otherwise, it may over- or under-estimate by an
    arbitrary amount. The result will be an integer >= 0.
    """
    try:
        return len(obj)
    except TypeError:
        try:
            get_hint = type(obj).__length_hint__
        except AttributeError:
            return default
        try:
            hint = get_hint(obj)
        except TypeError:
            return default
        if hint is NotImplemented:
            return default
        if not isinstance(hint, int):
            raise TypeError("Length hint must be an integer, not %r" %
                            type(hint))
        if hint < 0:
            raise ValueError("__length_hint__() should return >= 0")
        return hint

근거

__length_hint__로 추정한 예상 크기를 바탕으로 리스트를 미리 할당할 수 있으면 상당한 최적화가 될 수 있습니다. 순전히 이 최적화가 있다는 이유만으로 CPython이 일부 코드를 PyPy보다 빠르게 실행하는 것이 관찰되었습니다.