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

Mil*_*uss 4 python variables types function python-3.6

我使用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
Run Code Online (Sandbox Code Playgroud)

我期待,因为一个错误(或警告),bc不是整数.

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

wim*_*wim 5

目前,强制运行时验证仅由用户代码完成,例如使用第三方库.

一个这样的选择是强制执行:

>>> 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.
Run Code Online (Sandbox Code Playgroud)