Python 递归将字典、列表、元组、字节内容为字节转为节符串

需求:有时候读取redis的时候,会返回字典,并且内容为字节类型,此时需要转换,所以使用该函数轻松转换
注意:此代码来源Tornado源码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import typing
from typing import Any, Union,Optional

@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

unicode_type = str
_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)


def recursive_unicode(obj: Any) -> Any:
    """ 递归将字典、列表、元组、字节内容为字节转为节符串 """
    if isinstance(obj, dict):
        return dict(
            (recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
        )
    elif isinstance(obj, list):
        return list(recursive_unicode(i) for i in obj)
    elif isinstance(obj, tuple):
        return tuple(recursive_unicode(i) for i in obj)
    elif isinstance(obj, bytes):
        return to_unicode(obj)
    else:
        return obj
if __name__ == '__main__':
    li = {b'a': 'a', b'c': b'123'}
    print(recursive_unicode(li))

 

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