How can I assert that the argument only contains listed integers in Python

Viewed 1419

I have a method in Python and I only want to accept integers listed or singular, how can I define this?

def autoInt(integers):
    assert int(integers)
    assert len(integers) > 0

This fails as I cannot have a list. I'm sure it's something easy.

TypeError: int() argument must be a string or a number, not 'list'

Edit: I have been tasked so that this method can ONLY accept integers in a list.

3 Answers

That depends on what passes as an integer by your definition. For example, do instances of bool count? Does the float 1.0?

Anyway - you can combine the all builtin with a generator expression.

>>> a = [1,2,True]
>>> all(isinstance(x, int) for x in a)
True

As a sidenote: rigorously checking the argument types in not something Python programmers do when there's no specific reason. A better approach is usually to write clear docstrings and/or type hints.

Here is an answer which explains how to do the latter. Apart from that, there's usually a "garbage in -> garbage (or error)" out mentality.

>>> my_list = [1, 2, 3.25]
>>> all(isinstance(item, int) for item in my_list)
False
>>> other_list = range(3)
>>> all(isinstance(item, int) for item in other_list)
True
>>> 

Source: https://stackoverflow.com/a/6009630/6748523

Related