Search code examples
pythontype-conversionintarguments

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


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.


Solution

  • 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.