yann-qu

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  30 随笔 :: 0 文章 :: 2 评论 :: 36712 阅读

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
def show_count(count: int, singular: str, plural: Optional[str] = None) -> str:
# Quiz:
# plural: Optional[str] = None 和 plural: str = None的区别?
#
# Optional[str]是在type hint的层面说明这个参数是一个可选参数,但它并不能让该参数变成一个可选参数。
# 例如:
# def show_count(count: int, singular: str, plural: Optional[str]) -> str:
# 在这个声明中,type hint说明plural是一个可选参数,但它实际上并不是,不满足Python对于可选参数的语法要求。
# Remember: at run time, type hints are ignored! (Fluent Python, 2ed Edition, P260)
#
# str = None实在函数语法层面说明这个参数是一个可选参数。此时无论type hint怎么写,都不影响这个参数是一个可选参数的事实。
# 例如:
# def show_count(count: int, singular: str, plural: Optional[str] = None) -> str: # 声明1
# 在声明1中,= None在语法层面说明plural是一个可选参数,而且在type hint层面也说明plural是一个可选的str参数。
# def show_count(count: int, singular: str, plural: str = None) -> str: # 声明2
# 而在声明2中,= None在语法层面说明plural是一个可选参数,但在type hint层面只说明plural应该是一个str。
# 显然,此时type hint是不够准确的因为当plural缺省使用默认参数时,它是一个None,显然不是一个str。
#
# 相比于声明2,声明1的type hint显然更加准确。但这并不影响函数执行的结果。
# Remember: at run time, type hints are ignored! (Fluent Python, 2ed Edition, P260)
#
if count == 1:
return f'1 {singular}'
count_str = str(count) if count else 'no'
if not plural:
plural = singular + 's'
return f'{count_str} {plural}'
posted on   yann-qu  阅读(558)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示