How can I limit python function parameter to accept only arrays of some fixed-size?
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.
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:
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):
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.
assert for things that may happen in production (i.e. outside of test cases): it will only raise an exception if __debug__ is falsey. See the documentation.collections.abc.Sequence. Type checking, if you ever do it, should also use isinstance, rather than type. So you want something like if not isinstance(a, collections.abc.Sequence):If you don't mind unpacking your arg list then you could do this to limit the second arg to a fixed size collection of two elements.
> def f(a,(b1,b2), c):
b=[b1,b2]
print(a)
print(b)
print(c)
Examples :
# ok to call with 2 elem array
> b=[1,2]
> f("A",l,"C")
A
[1, 2]
C
# but falls if call with other size array
> b=[1,2,3]
> f("A",b,"C")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
ValueError: too many values to unpack
# btw also ok if call with 2 elem tuple
> f("A",(1,2),"B")
A
[1, 2]
C
lists? Wouldn't other sequences be acceptable? And why exactly two elements? What do they represent? Why do you want them in alistas opposed to being passed as two separate arguments?