简体   繁体   中英

How to limit function parameter as array of fixed-size?

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.

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM