【问题标题】:return type and actual return type [closed]返回类型和实际返回类型
【发布时间】:2021-03-11 11:43:28
【问题描述】:
def f(x: int) -> str:
    return 0

对于上面的函数,我怎么能提出AssertionError,因为函数应该返回一个str类型,但它返回一个int类型?

【问题讨论】:

  • 如果您正在编写函数,并且知道它应该返回一个字符串,为什么不确保它确实返回一个字符串(或者可能是None)?作为程序员,你有责任确保你创建的代码没有错误。
  • @Someprogrammerdude 我这样做是因为我目前正在编写一个检查函数注释的类对象,所以我需要在我的类中指定这种错误
  • 你应该如何检查注释?你是在做静态分析,还是运行时分析?请edit您的问题向我们提供有关您的目标、您正在做什么以及您正在解决的问题的详细信息。

标签: python function types


【解决方案1】:

如果你想输入检查你的函数,你可以通过两种方式做到这一点:

在运行时:

def f(x: int) -> str:
    result = "" # Initialize your return value here
    # ... manipulate result variable here
    assert isinstance(result, str) # This will cause AssertionError if result is not a str.
    return result

或者,您可以使用 python 类型检查器,例如 MyPy。如果你习惯在 Python 代码中编写类型提示,我认为第二种方法更优雅。

【讨论】:

    【解决方案2】:

    如果您在函数中引发断言错误,则执行将停止并且您不会获得实际返回。以下代码段打印异常和实际返回类型。

    def f(x: int) -> str:
        return x
    
    output = f(0)
    
    # Check if the function returned a result with the correct type.
    try:
        assert isinstance(output, str)
    except AssertionError as err:
        err.args += (f'Parameter {type(output)}', 'expected str')
        print(repr(err))
    
    print(output)
        
    

    输出:

    AssertionError("Parameter <class 'int'>", 'expected str')
    0
    

    【讨论】:

    • @Alex 看看我更新的答案,告诉我它是否适合你。如果没有,我们可以进行一些更改。
    猜你喜欢
    • 2017-06-07
    • 2018-11-19
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2019-08-04
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多