Python Type Hint中Optional[str]=None和str=None的区别

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}'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值