python - 如何在不使用断言的情况下指定函数输入和输出的类型?
问题描述
我正在使用 Python 3.6 并想定义一个接受两个整数a
并b
返回它们的除法的函数c = a//b
。我想强制输入和输出类型而不使用assert
. 根据我在文档和本网站上的发现,我的理解是应该这样定义这个函数:
def divide(a: int, b: int) -> int:
c = a // b
return c
divide(3, 2.) # Output: 1.0
我期待一个错误(或警告),因为b
并且c
不是整数。
- 我的特定代码有什么问题?
- 如何
assert
在不使用一般情况下正确指定输入和输出类型?
解决方案
强制运行时验证目前仅由用户代码完成,例如使用 3rd 方库。
一种这样的选择是强制执行:
>>> import enforce # pip install enforce
>>> @enforce.runtime_validation
... def divide(a: int, b: int) -> int:
... c = a // b
... return c
...
...
>>> divide(3, 2.0)
RuntimeTypeError:
The following runtime type errors were encountered:
Argument 'b' was not of type <class 'int'>. Actual type was float.
推荐阅读
- android - Playstore 开放测试的意义
- python-3.x - 有没有办法将形状绘制到 numpy 数组上?
- javascript - 我在 Firebase 存储上获得多个文件的相同 url
- databricks - ADF 连接到本地 Db 并使用 DBFS 进行转换。在 Delta 湖中保留副本有什么好处吗?
- xcode - xcodebuild 在启动时崩溃
- php - 根据准备好的语句的结果分配对象属性
- html - 如何使“下一步”按钮在 HTML 中工作?
- ios - 异步块中 Any 与 Void 的返回之间的区别
- html - 如何在不使用 html 标签的情况下更改单词的颜色?
- push-notification - 在 FCM 中处理延迟的未注册令牌