How to test that a function only accepts a certain type?
<p>I want to ensure that <code>twist_data</code> only gets a list of integers as an argument, and add a unit test.</p>

<pre><code> def twist_data(n):
     n=list(n)
     a=[]
     b=[]
     for i in n:
         if i&lt;=0:
             a.append(i)
         if i&gt;0:
             b.append(i)
     n=[len(a),sum(b)]
     return n


 gum=[2,4,5,-6,-7,]
 print (twist_data (gum))
</code></pre>

<pre><code>def all_ints(numbers):
    return all(isinstance(number, int) for number in numbers)


def validate_list(numbers):
    return all((isinstance(numbers, list), all_ints(numbers))


def twist_data(numbers):
    if not validate_list(numbers):
        raise TypeError('"numbers" must be of type "list", where all elements integers')
    positives, negatives = [], []
    for number in numbers:
        if number &lt;= 0:
            negatives.append(number)
        if i &gt; 0:
            positives.append(number)
    return [len(negatives), sum(positives)]
</code></pre>

<p>While not generally Pythonic to do explicit type checking sometimes it's unavoidable. This is a pretty straight forward way to do so. However it's easier to ask for forgiveness than to ask for permission so this is another possibility:</p>

<pre><code>def twist_data(numbers):
    positives, negatives = [], []
    try:
        for number in numbers:
            if number &lt;= 0:
                negatives.append(number)
            if i &gt; 0:
                positives.append(number)
        return [len(negatives), sum(positives)]
    except TypeError:
        raise TypeError('"numbers" must be of type "list", where all elements integers')
</code></pre>

<p>Here a <code>TypeError</code> is raised if you try to do a comparison between non-comparable types. You can then catch the exception and reraise with your own message. </p>

<p>Also do try to avoid single letter variable names. It'll be much easier to keep track of what's going on.</p>

python unit-testing