确保函数的输入参数是int/str的Pythonic方法?

2024-04-27 23:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,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的方式?你知道吗

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


Tags: namenoneinput参数returnfooistype
3条回答

您最终可以使用一些数据验证库,比如Cerberus,但正如jonsharpe在一篇评论中所说的,常见的方法是让python通过简单地将输入转换成整数来处理错误。你知道吗

只要做:

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

请看那里,了解更多关于这个主题的信息:https://stackoverflow.com/a/154156/4279120

您可以使用type hints来获得IDE对类型的支持(IDE会告诉您是否传递了错误的类型)。。。无论如何,没有什么可以阻止在运行时传递错误的类型,因此您可以在下面的代码段中检查它,如果接收到的对象不是预期的对象,则引发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

我觉得你把事情搞得太复杂了

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')

相关问题 更多 >