【问题标题】:Pythonic way of ensuring that input argument to a function is int/str? [duplicate]确保函数的输入参数是 int/str 的 Pythonic 方式? [复制]
【发布时间】:2020-01-03 11:37:28
【问题描述】:

基本上foo() 期望的参数应该作为int 传递,但也有可能有人将它作为str 传递(如果str 可以转换为int 也有效) .这是我想出的:

def foo(input_argument):
    func_name = 'foo'

    if type(input_argument) is not int or type(input_argument) is not str:
        print(
            '%s: "input_argument" expects int/str, not %s' % (
                func_name,
                type(input_argument)
            )
        )
        return None
    try:
        input_argument= int(input_argument)
    except:
        print(
            '%s: "input_argument" expects number in str/int format' % func_name
        )
        return None

是否有内置的东西可以以更 Python 的方式简化它?

编辑:布尔类型应被视为无效

【问题讨论】:

  • 坦率地说,我只是将其简化为input_argument = int(input_argument)。如果它已经是一个 int,那么这是一个空操作,如果可能,解析一个字符串,如果它是一个字符串但不能解析为一个 int,则抛出一个 ValueError,或者抛出一个 TypeError。而且你几乎不应该使用裸露的except:
  • @jonrsharpe 也许我应该说 True 也不是有效的输入参数类型
  • 为什么不是?
  • 嗯,从技术上讲是这样,但从“功能性”的角度来看,它不是
  • 为什么这个问题被标记为python-2.7?

标签: python python-2.7


【解决方案1】:

你最终可以使用一些数据验证库,比如Cerberus,但就像 jonsharpe 在评论中所说,常见的方法是让 python 处理错误,只需尝试将输入转换为整数。

只要做:

def foo(input_argument):
    input_argument= int(input_argument)
    # ... your method

在此处查看有关该主题的更多信息:https://stackoverflow.com/a/154156/4279120

【讨论】:

  • 我们运行这些脚本的自定义环境并不真正支持鸭子类型,如果发生异常就会中断,所以我们必须自己处理这些异常,但我明白了!
【解决方案2】:

我认为你把事情复杂化了

import sys

def foo(input_argument):
    try:
        input_argument = int(input_argument)
    except Exception:
        print('Unexpected error occured: %s' % sys.exc_info()[1])

或者更好的错误处理

def foo(input_argument):
    try:
        input_argument = int(input_argument)
    except ValueError:
        print('That is not a number, but a string')
    except TypeError:
        print('That is not a number')

【讨论】:

    【解决方案3】:

    您可以使用type hints 来获得 IDE 对类型的支持(如果您传递了错误的类型,IDE 会告诉您)...无论如何,没有什么可以阻止在运行时传递错误的类型,因此您可以将其检查为在下面的 sn-p 中,如果接收到的对象不是预期的对象,则引发 ValueError

    def foo(input: Union[int, str]):
        if not isinstance(input, (int, str)):
            raise ValueError(f'Invalid input, expected int or str, got: "{type(input)}"')
    
        # ...implementation
    

    【讨论】:

    • 帖子标记为python 2.7;您在此处使用的语法仅适用于 Python 3。 Mypy 和 PyCharm 支持 cmets 中的提示,使用这些提示。
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多