Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
9  
Type Hints are expected to be shipped with Python 3.5, which is not ready yet. –  myaut 6 hours ago
    
My recommendation would be more closely related to what specifically you're trying to accomplish. Why only lists? Wouldn't other sequences be acceptable? And why exactly two elements? What do they represent? Why do you want them in a list as opposed to being passed as two separate arguments? –  Blacklight Shining 1 hour ago

2 Answers 2

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
share|improve this answer
1  
raise ValueError would be better. –  myaut 5 hours ago
    
agreed. Thanks. –  Totem 5 hours ago

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 type(a) is not list:
        raise TypeError("The variable has a wrong type")
    elif len(a) != 2:
        raise ValueError("Wrong length given for list")
    # rest goes here

2nd way (only for debugging)

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

def func(a):
    assert type(a) is list and len(a) == 2, "Wrong input given."
    # rest goes here

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

share|improve this answer
    
No, don't use 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. –  Blacklight Shining 4 hours ago
    
Ok, I've updated the answer. –  naltipar 3 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.