Python Type Hint中Optional[str]=None和str=None的区别
1 问题来源
在读到Fluent Python, 2ed Edition, P260时产生了一些疑问:
在Python中使用type hint时,以下两个声明有什么区别呢?
def show_count(count: int, singular: str, plural: Optional[str] = None) -> str: # 声明1
def show_count(count: int, singular: str, plural: str = None) -> str: # 声明2
2 个人见解
# -*- coding: utf-8 -*-
# @Time : 2022/12/19 14:53
# @File : messages.py
# @Description : None
# @Author : Yann
from typing import Optional
from typing import Union
# def show_count(count: int, singular: str, plural: Optional[str] = None) -> str:
# or
# def show_count(count: int, singular: str, plural: str | None = None) -> str: # in Python 3.10
# or
def show_count(count: int, singular: str, plural: Union[str, None] = None) -> str:
# Quiz:
# plural: Optional[str] = None 和 plural: str = None的区别?
#
# Optional[X] is equivalent to X | None (or Union[X, None]).
# Note that **this is not the same concept as an optional argument**, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:
# def foo(arg: int = 0) -> None: ...
# On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:
# def foo(arg: Optional[int] = None) -> None: ...
# 总结:可选参数与Optional关键字没有必然联系。
if count == 1:
return f'1 {singular}'
count_str = str(count) if count else 'no'
if not plural: # 没有特殊的复数形式,直接加s
plural = singular + 's'
return f'{count_str} {plural}'