【问题标题】:How to specify the type of a function input and output without using assert?如何在不使用断言的情况下指定函数输入和输出的类型?
【发布时间】:2018-11-18 23:31:10
【问题描述】:

我正在使用 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. 如何在不使用的情况下正确指定输入和输出类型 assert 一般?

【问题讨论】:

  • Python 本身从不强制执行变量、参数或返回类型。它是一种动态类型语言
  • 他们被称为type hints 是有原因的。解释器根本不使用它们,尽管它们在运行时可作为对象属性使用。

标签: python function variables types python-3.6


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2022-08-09
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2021-07-18
    • 2020-01-25
    相关资源
    最近更新 更多