Python - typing 模块 —— Any Type

简介: Python - typing 模块 —— Any Type

前言


typing 是在 python 3.5 才有的模块

 

前置学习

Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html

 

常用类型提示


https://www.cnblogs.com/poloyy/p/15150315.html

 

类型别名


https://www.cnblogs.com/poloyy/p/15153883.html

 

NewType


https://www.cnblogs.com/poloyy/p/15153886.html

 

Callable


https://www.cnblogs.com/poloyy/p/15154008.html

 

TypeVar 泛型


https://www.cnblogs.com/poloyy/p/15154196.html

 

Any Type


  • 一种特殊的类型是 Any
  • 静态类型检查器会将每种类型都视为与 Any 兼容,将 Any 视为与每种类型兼容

 

小栗子

# Any
from typing import Any
a = None  # type: Any
a1 = []  # OK
a2 = 2  # OK
s = ''  # type: str
s1 = a  # OK
def foo(item: Any) -> int:
    # Typechecks; 'item' 可以是任意类型
    print(item)
    return 1
foo(a)
foo(a1)
foo(a2)
foo(s)
foo(s1)


隐式使用 Any

def legacy_parser(text):
    ...
    return data
# 上述写法等价于下述写法
# 所有没有返回类型或参数类型的函数将隐式默认使用 Any
def legacy_parser(text: Any) -> Any:
    ...
    return data


Union


https://www.cnblogs.com/poloyy/p/15170066.html

 

Optional


https://www.cnblogs.com/poloyy/p/15170297.html

相关文章
|
2天前
|
Python
[oeasy]python036_数据类型有什么用_type_类型_int_str_查看帮助
本文回顾了Python中`ord()`和`chr()`函数的使用方法,强调了这两个函数互为逆运算:`ord()`通过字符找到对应的序号,`chr()`则通过序号找到对应的字符。文章详细解释了函数参数类型的重要性,即`ord()`需要字符串类型参数,而`chr()`需要整数类型参数。若参数类型错误,则会引发`TypeError`。此外,还介绍了如何使用`type()`函数查询参数类型,并通过示例展示了如何正确使用`ord()`和`chr()`进行转换。最后,强调了在函数调用时正确传递参数类型的重要性。
10 3
|
1天前
|
Go Python
通过 atexit 模块让 Python 实现 Golang 的 defer 功能
通过 atexit 模块让 Python 实现 Golang 的 defer 功能
10 2
|
10天前
|
JSON API 数据格式
30天拿下Python之requests模块
30天拿下Python之requests模块
23 7
|
10天前
|
人工智能 数据可视化 搜索推荐
Python异常模块与包
Python异常模块与包
|
9天前
|
Linux Python Windows
一个Python模块Pendulum的问题
一个Python模块Pendulum的问题
16 0
|
10天前
|
API Python
30天拿下Python之matplotlib模块
30天拿下Python之matplotlib模块
|
10天前
|
SQL 数据处理 数据库
30天拿下Python之pandas模块
30天拿下Python之pandas模块
12 0
|
10天前
|
存储 索引 Python
30天拿下Python之numpy模块
30天拿下Python之numpy模块
13 0
|
10天前
|
开发者 Python
30天拿下Python之logging模块
30天拿下Python之logging模块
|
10天前
|
安全 索引 Python
30天拿下Python之collections模块
30天拿下Python之collections模块