0

I'm creating a function right now that takes in two lists. I want these two lists to be of equal size. I'm trying to figure out what kind of exception I should throw (or If I should throw an exception at all) if they aren't the same size. I kind of want to say ValueError but this is a check that doesn't actually pertain to any single value.

For clarities sake, here's my function stub.

def create_form(field_types, field_discriptions):
    pass
3
  • 1
    ValueError seems good. string.maketrans (str.maketrans in Python 3.x) raises ValueError unless two arguments have same length. Commented Aug 1, 2013 at 3:31
  • I think in this case assert is the better choice because I'm making an innate assumption about the values being passed to the function. I think in my particular case I want to reserve ValueError for if someone passes me a wrong field type. Commented Aug 1, 2013 at 3:36
  • 1
    Raise TypeError if wrong field type passed. Commented Aug 1, 2013 at 3:38

3 Answers 3

1

I would just use assert and raise an AssertionError:

assert len(field_types) == len(field_descriptions), "Helpful message"

Otherwise, ValueError with a message seems like the best choice.

Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe I forgot about asserts. This feels like the right answer to me.
1

You can create your own subclass of exception called ArraysNotEqualSizeException. Might be a bit overkill, but it gets the point across.

Comments

1

throw an exception as the first thing in the function. A function-critical error should not do anything without making sure it can do what it wants or it could have bad effects

This isn't a giant error; you should use an assert

Places to consider putting assertions:

checking parameter types, classes, or values checking data structure invariants checking "can't happen" situations (duplicates in a list, contradictory state variables.) after calling a function, to make sure that its return is reasonable -Python wiki

assert len(listone) == len(listtwo), 
    "the function cannot continue because\
     the two arguments passed are of invalid length"

a ValueError as suggested by Blender would be the right type if you want to use a generic exception, however that's usually reserved for larger issues and would be less helpful.

for quick reference:

"ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError." -Python docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.