Python-类型提示-类型注释符号(定义变量时指定数据类型)

 typing 是在 python 3.5 才有的模块

 

# Python-类型提示-类型注释符号
##########################################
# 变量
##########################################
# This is how you declare the type of a variable type in Python 3.6
age: int = 1
# In Python 3.5 and earlier you can use a type comment instead
# (equivalent to the previous definition)
age = 1 # type: int
# You don't need to initialize a variable to annotate it
a: int # Ok (no value at runtime until assigned)
# The latter is useful in conditional branches
child: bool
if age < 18:
    child = True
else:
    child = False
##########################################
# 内置类型
##########################################
from typing import List, Set, Dict, Tuple, Optional
# For simple built-in types, just use the name of the type
x: int = 1
x: float = 1.0
x: bool = True
x: str = "test"
x: bytes = b"test"
# For collections, the name of the type is capitalized, and the
# name of the type inside the collection is in brackets
x: List[int] = [1]
x: Set[int] = {6, 7}
# Same as above, but with type comment syntax
x = [1] # type: List[int]
# For mappings, we need the types of both keys and values
x: Dict[str, float] = {'field': 2.0}
# For tuples of fixed size, we specify the types of all the elements
x: Tuple[int, str, float] = (3, "yes", 7.5)
# For tuples of variable size, we use one type and ellipsis
x: Tuple[int, ...] = (1, 2, 3)
# Use Optional[] for values that could be None
x: Optional[str] = some_function()
# Mypy understands a value can't be None in an if-statement
if x is not None:
    print(x.upper())
# If a value can never be None due to some invariants, use an assert
assert x is not None
print(x.upper())
##########################################
# 功能
##########################################
from typing import Callable, Iterator, Union, Optional, List
# This is how you annotate a function definition
def stringify(num: int) -> str:
    return str(num)
# And here's how you specify multiple arguments
def plus(num1: int, num2: int) -> int:
    return num1 + num2
# Add default value for an argument after the type annotation
def f(num1: int, my_float: float = 3.5) -> float:
    return num1 + my_float
# This is how you annotate a callable (function) value
x: Callable[[int, float], float] = f
# A generator function that yields ints is secretly just a function that
# returns an iterator of ints, so that's how we annotate it
def g(n: int) -> Iterator[int]:
    i = 0
    while i < n:
        yield i
        i += 1
# You can of course split a function annotation over multiple lines
def send_email(address: Union[str, List[str]],
               sender: str,
               cc: Optional[List[str]],
               bcc: Optional[List[str]],
               subject='',
               body: Optional[List[str]] = None
               ) -> bool:
    ...
# An argument can be declared positional-only by giving it a name
# starting with two underscores:
def quux(__x: int) -> None:
    pass
quux(3) # Fine
quux(__x=3) # Error
##########################################
# 标准"duck_types"
# 在典型的Python代码中,许多可以将list或dict作为参数的函数只需要它们的参数以某种方式“list-like”或“dict-like”。“list-
# like”或“dict-like”(或其他类似的)的特定含义称为“duck-type”,并且标准化了惯用Python中常见的几种duck类型。
##########################################

 

 Callable[..., Any],可调用者接受任意数量的/类型的参数并返回任何类型的值。

 

pretrained_model_name_or_path: Optional[Union[str, os.PathLike]]

`str` or `os.PathLike`

 

 

前置学习

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

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

 

Union

联合类型

Union[int, str] 表示既可以是 int,也可以是 str

 

等价写法

 
vars: Union[int, str]
# 等价于
vars: [int or str]


vars: Union[int]
# 等价于
vars: int
 

 

union 等价写法

 
Union[int] == int

最终 Union[int] 返回的也是 int 类型

 

 
Union[int, str, int] == Union[int, str]

重复的类型参数会自动忽略掉

 

 
Union[int, str] == Union[str, int]

自动忽略类型参数顺序

 

 
Union[Union[int, str], float] == Union[int, str, float]

union 嵌套 union 会自动解包

 

Optional

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

 

 

REF:

https://wenku.baidu.com/view/665fca1364ec102de2bd960590c69ec3d5bbdb7b.html

 

posted @ 2022-05-14 18:39  emanlee  阅读(191)  评论(0编辑  收藏  举报