首页 > 解决方案 > 如何在不使用断言的情况下指定函数输入和输出的类型?

问题描述

我正在使用 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

我期待一个错误(或警告),因为b并且c不是整数。

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

标签: pythonfunctionvariablestypespython-3.6

解决方案


强制运行时验证目前仅由用户代码完成,例如使用 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.

推荐阅读