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}'

Python Type Hint中Optional[str]=None和str=None的区别的更多相关文章

  1. Python type hints 之 Optional,Union

    1,前言 type hint 在pep484加入,我个人觉得这种类似于类型约束的(机制)有点违背了python简单.简洁的初衷,在慢慢向c# java 这种强类型语言看齐的节奏. 不过好在不强制使用, ...

  2. Python Type Hint类型注解

    原文地址:https://realpython.com/python-type-checking/ 在本指南中,你将了解Python类型检查.传统上,Python解释器以灵活但隐式的方式处理类型.Py ...

  3. Python工程文件中的名词解释---Module与Package的区别

    当我们在已有的Python工程文件中创建新的内容是,通常会有两种类型文件供你选择---Module和Package,对于初学者来说会搞不清楚这两种文件直接的关系.这里就来解释一下这两者之间的关系. M ...

  4. python time包中的time.time()和time.clock()的区别

    在统计python代码 执行速度时要使用到time包,在查找相关函数时有time.time()和time.clock()两个函数可供选择.而两者是有区别的: cpu 的运行机制:cpu是多任务的,例如 ...

  5. python 读写文件中 w与wt ; r与rt 的区别

    w,r,wt,rt都是python里面文件操作的模式.w是写模式,r是读模式.t是windows平台特有的所谓text mode(文本模式),区别在于会自动识别windows平台的换行符.类Unix平 ...

  6. Python type类具体的三大分类:metaclasses,classes,instance

    Python type类视角中的对象体系需要我们不断的学习,其中我们使用的时候需要注意.下面我们就看看如何才能更好的运用Python type类.下面的文章希望大家有所收获. 在单纯的Python t ...

  7. python开发_python中str.format()

    格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过 下面看看python中的字符串格式函数str.format(): 1 #使用str.format()函数 2 3 #使用 ...

  8. python TypeError: unsupported operand type(s) for +: 'geoprocessing value object' and 'str'

    TypeError: unsupported operand type(s) for +: 'geoprocessing value object' and 'str' if self.params[ ...

  9. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 3、Python Basics with numpy (optional)

    Python Basics with numpy (optional)Welcome to your first (Optional) programming exercise of the deep ...

  10. python 中的input()和raw_input()功能与使用区别

    在python中raw_input()和input()都是提示并获取用户输入的函数,然后将用户的输入数据存入变量中.但二者在处理返回数据类型上有差别. input()函数是raw_intput()和e ...

随机推荐

  1. std::string实现split和trim方法

    void split(const std::string& str, const std::string& strDelimiter, std::vector<std::stri ...

  2. 当FTP不能满足大文件、海量文件传输时,有没有好的替代方案?

    很多企业存在大文件.海量文件的传输需求,如涉及到图像数据采集和回传.海量用户数据收集和同步等业务,一般情况,企业还是会采用传统的FTP传输,或者以此为基础,使用脚本或结合其他办公工具来解决传输需求. ...

  3. kubernetes 报错The connection to the server localhost:8080 was refused - did you specify the right host or port?

    The connection to the server localhost:8080 was refused - did you specify the right host or port? 环境 ...

  4. evalJS代替mui.fire

    之前一直用mui.fire调用自定义事件以达到监听目标窗口的目的. 页面为双webview,页面跳转时 mui.openWindow({ url: '../choose/food-choose-con ...

  5. 宽字符集(unicode)操作函数 (转)

    字符分类: 宽字符函数 普通C函数 描述 iswalnum() isalnum() 测试字符是否为数字或字母 iswalpha() isalpha() 测试字符是否是字母 iswcntrl() isc ...

  6. locust socektio协议压测

    # -*-coding:UTF-8 -*- from locust import HttpLocust, TaskSet, task, TaskSequence, Locust, events imp ...

  7. JS篇(005)-== 和 === 的不同

    答案:==是抽象相等运算符,而===是严格相等运算符.==运算符是在进行必要的类型转换后,再比较.===运算符不会进行类型转换,所以如果两个值不是相同的类型,会直接返回false.使用==时,可能发生 ...

  8. 微信小程序云开发,快速生成短信验证码

    使用微信小程序云函数实现注册短信验证码的管理,并不是一件分分钟的事,目前想要存储验证码只能放到数据库中,因为存储后才能和用户提交上来的验证码做比较. 管理验证码主要涉及到:生成.存储.校验.有效期管理 ...

  9. java发送短信验证码带倒计时

    分享一个完整的java发送短信验证码的完整实例,这是一个官方的使用demo,带有60秒倒计时功能. 效果: 我使用的是榛子云短信平台, 官网地址:http://smsow.zhenzikj.com 我 ...

  10. 20202411 2020-2021-2 《Python程序设计》实验一报告

    20202411 2020-2021-2 <Python程序设计>实验一报告 课程:<Python程序设计> 班级: 2024 姓名: 陈书桓 学号:20202411 实验教师 ...