如何将函数参数限制为固定大小的数组?

时间:2021-09-12 03:08:53

How can I limit python function parameter to accept only arrays of some fixed-size?

如何限制python函数参数只接受一些固定大小的数组?

I tried this but it doesn't compile:

我试过这个,但它没有编译:

def func(a : array[2]):

with

TypeError: 'module' object is not subscriptable

I'm new to this language.

我是这种语言的新手。

2 个解决方案

#1


10  

What about checking the length inside of the function? Here I just raised an error, but you could do anything.

检查函数内部的长度怎么样?我刚刚提出错误,但你可以做任何事情。

def func(array):
    if len(array) != 2:
        raise ValueError("array with length 2 was expected")
    # code here runs if len(array) == 2

#2


6  

1st way (you'll most probably want to use this)

第一种方式(你很可能想要使用它)

You can just check for all the criteria inside your function by using if statements:

您可以使用if语句检查函数内的所有条件:

def func(a):
    if not isinstance(a, collections.abc.Sequence):
        raise TypeError("The variable has a wrong type")
    elif len(a) != 2:
        raise ValueError("Wrong length given for list")
    # rest of the code goes here

2nd way (only for debugging)

第二种方式(仅用于调试)

You can use assert as a workaround solution (meant for debugging):

您可以使用assert作为解决方案解决方案(用于调试):

def func(a):
    assert isinstance(a, collections.abc.Sequence) and len(a) == 2, "Wrong input given."
    # rest of the code goes here

So this will check if both criteria are met, otherwise an assertion error will be raised with the message Wrong Input Type.

因此,这将检查是否满足两个条件,否则将引发错误输入类型消息的断言错误。

#1


10  

What about checking the length inside of the function? Here I just raised an error, but you could do anything.

检查函数内部的长度怎么样?我刚刚提出错误,但你可以做任何事情。

def func(array):
    if len(array) != 2:
        raise ValueError("array with length 2 was expected")
    # code here runs if len(array) == 2

#2


6  

1st way (you'll most probably want to use this)

第一种方式(你很可能想要使用它)

You can just check for all the criteria inside your function by using if statements:

您可以使用if语句检查函数内的所有条件:

def func(a):
    if not isinstance(a, collections.abc.Sequence):
        raise TypeError("The variable has a wrong type")
    elif len(a) != 2:
        raise ValueError("Wrong length given for list")
    # rest of the code goes here

2nd way (only for debugging)

第二种方式(仅用于调试)

You can use assert as a workaround solution (meant for debugging):

您可以使用assert作为解决方案解决方案(用于调试):

def func(a):
    assert isinstance(a, collections.abc.Sequence) and len(a) == 2, "Wrong input given."
    # rest of the code goes here

So this will check if both criteria are met, otherwise an assertion error will be raised with the message Wrong Input Type.

因此,这将检查是否满足两个条件,否则将引发错误输入类型消息的断言错误。