Python encode与decode完美封装

需求:字符串转为字节,字节转为字符串,这个是网络编程最常用的需求
注意:此代码来源Tornado源码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import typing
from typing import Optional, Union

unicode_type = str

_UTF8_TYPES = (bytes, type(None))
@typing.overload
def utf8(value: bytes) -> bytes:
    pass


@typing.overload  # noqa: F811
def utf8(value: str) -> bytes:
    pass

@typing.overload  # noqa: F811
def utf8(value: None) -> None:
    pass

def utf8(value: Union[None, str, bytes], code_type='utf-8') -> Optional[bytes]:  # noqa: F811
    """ utf-8编码"""
    if isinstance(value, _UTF8_TYPES):
        return value
    if not isinstance(value, unicode_type):
        raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
    return value.encode(code_type)

@typing.overload
def to_unicode(value: str) -> str:
    pass

@typing.overload  # noqa: F811
def to_unicode(value: bytes) -> str:
    pass

@typing.overload  # noqa: F811
def to_unicode(value: None) -> None:
    pass

_TO_UNICODE_TYPES = (unicode_type, type(None))

def to_unicode(value: Union[None, str, bytes], code_type='utf-8') -> Optional[str]:  # noqa: F811
    """字节类型转为字符串"""
    if isinstance(value, _TO_UNICODE_TYPES):
        return value
    if not isinstance(value, bytes):
        raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
    return value.decode(code_type)

if __name__ == '__main__':
    s = utf8('中国')
    print('编码:', s)
    ret = to_unicode(s)
    print('解码:', ret)
运行结果
编码: b'\xe4\xb8\xad\xe5\x9b\xbd'
解码: 中国

 

posted @ 2020-11-23 11:56  小粉优化大师  阅读(144)  评论(0编辑  收藏  举报