變數: 型別
方式加入,回傳 return 值的型別,則在函式後面的 :
前,以 -> 型別
來進行,如 def fun() -> str:
def get_str(s):
return f"this is {s}"
# 加入 type hint
def get_str(s: int) -> str:
return f"this is {s}"
from typing import List, Dict
# 3.9 以上(含)
def test(x: list[int]):
pass
word_json: dict[str, int] = {
"a": 1,
"b": 2
}
# 3.9 以下
from typing import List, Dict
def test(x: List[int]):
pass
word_json: Dict[str, int] = {
"a": 1,
"b": 2
}
|
取代from typing import Union
# 3.10 以上(含)
T = str | int
def concat(a: T, b: T) -> T:
return a + b
# 3.10 以下
from typing import Union
T = Union[str, int]
def concat(a: T, b: T) -> T:
return a + b
|
,X | None
from typing import Optional
# 3.10 以上(含)
def foo(arg: int | None) -> None:
pass
# 3.10 以下
from typing import Optional
def foo(arg: Optional[int] = None) -> None:
pass
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
def student_to_string(s: Student) -> str:
return f"student name: {s.name}, age: {s.age}."
student_to_string(Student("Tim", 18))
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
簡單介紹 venv(虛擬環境)與 env(環境變數)