銀月の符号

Python 使い見習いの日記・雑記

『065:文字列を最大nバイトに切り詰める』は codecs モジュールまかせでもできるような気がしてきた

codecs の Python ソースにこのようなものをみつけた。

def iterdecode(iterator, encoding, errors='strict', **kwargs):
    """
    Decoding iterator.

    Decodes the input strings from the iterator using a IncrementalDecoder.

    errors and kwargs are passed through to the IncrementalDecoder
    constructor.
    """
    decoder = getincrementaldecoder(encoding)(errors, **kwargs)
    for input in iterator:
        output = decoder.decode(input)
        if output:
            yield output
    output = decoder.decode("", True)
    if output:
        yield output

なにぃっ!? getincrementaldecoder ? IncrementalDecoder
少し手を加えたら、レシピそのものになってしまうじゃないか。

Unicode 文字列から n バイト以内かつ中途半端でない 8 ビット文字列(or byte 型)を生成するのも IncrementalEncoder で終了の予感。