Opengist

Explore

  • All gists
  • Topics
  • Users
Give feedback on the new UI Powered by Opengist ⋅ 17ms

user:thomas gists created by user

title:mygist gists with given title

description:sync gists with given description

filename:myfile.txt gists having files with given name

extension:yml gists having files with given extension

language:go gists having files with given language

topic:homelab gists with given topic

all:systemctl search all fields

Login
s

static-analysis

Recently created Least recently created Recently updated Least recently updated

timmy / 使用 typing 進行型別註解

Last active 7 hours ago python static-analysis type-hinting typing

typing 模組允許為 Python 變數、函式參數和回傳值指定型別,有助於提升程式碼可讀性、可維護性,並可搭配靜態分析工具(如 mypy)檢查型別錯誤。

0 0 0 1
1 from typing import Any, Dict, List, Optional, Tuple, Union
2
3 # 函式使用型別註解
4 def process_data(
5 data: List[Dict[str, Union[int, float]]],
6 metadata: Optional[Dict[str, Any]] = None
7 ) -> Tuple[int, float]:
8 """計算資料的總和與平均值"""
9 total = sum(item["value"] for item in data)
10 avg = total / len(data) if data else 0