python - 特殊参数的类型提示

标签 python type-hinting

考虑以下函数:

from datetime import date

def days_between(start_date: date, end_date: date) -> int:
    if start_date == "initial":
        start_date = date(2023, 9, 1)
    delta = end_date - start_date
    return delta.days 

开始日期的类型提示大部分都可以,但不包括 "initial" 的情况。已通过。这是唯一允许的字符串,你会如何表达它?

我想到的选项是:

  • start_date: date | str这似乎有点矫枉过正
  • start_date: date | "initial"也许没问题,但我还没有遇到过类似的事情
  • 无需更改,只需在文档字符串中添加说明

为了完整性,与静态类型检查的形式正确性相比,我更感兴趣的是如何向用户传达函数的使用。

最佳答案

您应该使用typing.Literal

from typing import Literal

def days_between(start_date: date | Literal['initial'], end_date: date) -> int:
    ...

从 python 3.8 开始包含此功能。

Literal 可用于向类型检查器指示带注释的对象具有与所提供的文字之一等效的值。

关于python - 特殊参数的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77022582/

相关文章:

python - 在一张图中而不是在多张图中绘制多个图形

python - 如何使用 Beautiful Soup 从网站检索信息?

Python 键入 : how to get Type[C] to work with TypeVars and Generics?

Python lxml : How to split comma separated data and find specific values from XML-file?

Python。无法从 None 错误中创建 fast_float

clojure - 在 Clojure 中获取函数的参数类型提示

python-3.x - Python 键入 : Create a class function with a generic type, 并通过类访问该类型

python-3.x - 具有 numpy ndarray 和 pandas dataframe 的 mypy 重载函数(签名参数类型相同或更广泛)

python - 你如何在 Python 中为一个类型起别名?

python - 具有灰色世界假设的自动白平衡