gpt4 book ai didi

python - 如何在不使用断言的情况下指定函数输入和输出的类型?

转载 作者:太空狗 更新时间:2023-10-30 02:37:15 25 4
gpt4 key购买 nike

我正在使用 Python 3.6 并想定义一个函数,它接受两个整数 ab 并返回它们的除法 c = a//b。我想在不使用 assert 的情况下强制执行输入和输出类型。根据我在文档和本网站上的发现,我的理解是应该这样定义此功能:

def divide(a: int, b: int) -> int:
c = a // b
return c

divide(3, 2.) # Output: 1.0

因为 bc 不是整数,所以我期待出现错误(或警告)。

  1. 我的特定代码有什么问题?
  2. 如何在不使用的情况下正确指定输入和输出类型断言一般?

最佳答案

强制执行运行时验证目前只能由用户代码完成,例如使用第 3 方库。

其中一个选择是 enforce :

>>> 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.

关于python - 如何在不使用断言的情况下指定函数输入和输出的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com