Python type hints調査

3577 ワード

Python type hints調査
参照リンク:
公式サイトhttps://docs.python.org/3/library/typing.html
https://ocavue.com/python_typing.html
https://blog.csdn.net/chuchus/article/details/77891128
https://www.cnblogs.com/erhuabushuo/p/10180789.html
1.function annotation
def plus(a: int, b: int = 2) -> int:
    return a + b

これはひとまず関数注記としてpython 3から訳す.0(PEP 3107参照).Pythonインタプリタは実行時にタイプをチェックしないので、パラメータのタイプが間違っていてもPythonインタプリタはそのために異常を投げ出すことはありません.
2.Python 3.5: typing
1.typingのベースタイプ
from typing import Dict, List
def best_students(scores: Dict[str, int]):
    return {name: score for name, score in scores.items if score >= 90}

Dict[str, int] keys str,values int , {"a": 1, "b": 2}.
List[int] [0, 1, 1, 2, 3].
Tuple[str,int]は,1つのメタグループに2つの要素があり,1つ目の要素はstrタイプ,2つ目はintタイプであることを示す.
typingが提供するタイプに基づいて、かなり複雑なネスト構造を書くことができます.
Dict[str, Dict[str, List[str]]]
{
    '   ': {
        '    ': ['  ', '  ', '  '],
        '    ': ['  ', '  '],
    },
    '   ': {
        '    ': ['  ', '  '],
        '    ': ['  ']
        '    ': ['  ', '   ']
    }
}

2.typingの高級タイプ
a.Union[None,str]はNoneまたはstrを表し、次の関数はNoneタイプ、またはstrタイプを返す
from typing import Union, List
​
def get_first_name(names: List[str]) -> Union[None, str]:
    if len(names) >= 1:
        return names[0]
    else:
        return None

b.Callable[[str,str],bool]は1つの関数を表し、2つのstrタイプの位置パラメータを受信し、戻り値はboolタイプである
from typing import Callable
​
def get_regex() -> Callable[[str, str], bool]:
    def regex(pattern: str, string: str) -> bool:
        return re
    return regex()

c.汎用(Generics)
pythonでは基本データ型(リスト、メタグループなど)を除き、基本データ型複合からなるデータ型(シーケンス、マッピング、コンテナ、反復器など)を複合データ型と呼ぶ.
複合型は、ここでは汎用型(Generics)と呼ぶ.typingには対応するクラスがあります.
from typing import Mapping, Sequence
​
def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: 
    pass

Sequence[Employee]は、シーケンスの要素がEmployeeタイプであるシーケンスを表します.
Mapping[str,str]はマッピングを表し,マッピングされたキーはstrタイプ,値はstrタイプである.
TypeVarは可変型の変数、パラメータを注釈するために使用され、typingのTypeVarによって汎用型の要素の下付き文字を注釈することができる.
from typing import Sequence, TypeVar
​
T = TypeVar('T')      #       
​
def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]

TypeVarがタイプ変数を宣言する場合、次の範囲を指定できます.
T = TypeVar('T')  # Can be anything
A = TypeVar('A', str, bytes)  # Must be str or bytes

d.Any、任意のタイプ
from typing import Any
​
def log(msg: Any):
    print(Any)

3.Python 3.6: variable annotations
変数注記
items: list = read_json_file()
class Employee(NamedTuple):
    name: str
    id: int = 3

4.__annotations__属性保存タイプ注記
>>> def foo(a: str):
...     print('hello', a)
...
​
>>> foo.__annotations__
{'a': str}
​
>>> class Bar:
...     a: str
...     b: int
​
>>> Bar.__annotations__
{'a': str, 'b': int}

5.python typingができないところ
a.キーワード参照
def foo(item: str) -> None:
    print(item + "s")
​
​
foo(item=0)

b.アクセサリー修飾の関数