TypeError: string argument without an encoding

這是從 python taiwan 發問的整理為以下

import struct
def nbytes_to_data(source):
    # 定義讀取函數
    read_bytes = lambda d, s: (d[:s], d[s:])
    read_files = lambda d, s: (d.read(s), d)
    read_socket = lambda d, s: (d.recv(s), d)
    readers = {
        bytes: read_bytes,
        list: read_bytes,
        str: read_bytes
    }
    # 定義bytes長度
    size_info = {'b': 1, "h": 2, "l": 4, "q": 8}
    # 由參數來決定使用哪個讀取函數
    reader = readers.get(type(source))
    if reader is None:
        raise TypeError('不支援的類型:' + str(type(source)))
    # 將資料切分為兩部分
    btag, source = reader(source, 1)
    # 轉換為 str 類型
    tag = btag.decode("utf-8") if isinstance(btag, bytes) else btag
    # 異常情況處理
    if tag in size_info:
    # 取得標籤代表的 bytes 長度
        size = size_info[tag]
        # 將資料切分為兩部分
        bnum, source = reader(source, size)
        result = struct.unpack('!' + tag, bytes(bnum))[0]
    elif tag in ['s', 'c']:
        size, source = nbytes_to_data(source)
        if size >= 65536:
            raise ValueError('長度過長:' + str(size))
            bstr, source = reader(source, size)
            result = bstr if tag == 's' else bstr.decode('utf-8')
    else:
        raise TypeError("無效的" + tag)
    return result, source

nbytes_to_data("hello,world")

會出現

result = struct.unpack('!' + tag, bytes(bnum))[0]
TypeError: string argument without an encoding

這個錯誤是出在 bytes(bnum) 缺少編碼方式
加上 bytes(bnum, "utf-8") 即可