首页 > 解决方案 > Python 3.6+ 可以是字符串或任何类的参数注释

问题描述

from typing import Union, Callable, Any

def map_type(t) -> str:
    if isinstance(t, str):
        _type = t
    else:
        _type = t.__name__
    return {
        'float': 'float',
        'int': 'integer',
        'number': 'float',
        'bool': 'boolean',
        'date': 'date',
        'datetime': 'datetime',
        'list': 'list',
        'str': 'string'
    }.get(_type)

那么注释t该怎么写呢?

def map_type(t: Union[str, Any])->str: pass

标签: python-3.xannotations

解决方案


不是任何对象,而是任何类?类的类型是type

>>> type(int)
type
>>> type(str)
type

因此,您可能想要 str 和 type 的联合,

def map_type(t: Union[str, type]) -> str:
    ...

Any类型仅表示“未检查类型”,这在联合中是无用的。


推荐阅读