Search code examples
pythonunit-testingdynamic-languages

How to deal with wrong parameters types in dynamic-languages?


I can't find the answer on SO but it's very likely that the argument has been already discussed.

I'm trying to write a quite small size program using the Python language. It's my first "real" experience with a dynamic language and I would prefer to do everything in the right way. One of the practice that I would try to apply since the beginning is unit-testing.

How can I quickly test that the parameters of a method are of the right type? Should I do it?

With right type I mean for instance to check that a method that works with float numbers is not called with a String. In this case consider the possibility that the method should obviously accept even integers and not only float.


Solution

  • How can I quickly test that the parameters of a method are of the right type?

    The quickest way is to do nothing.

    Seriously. The dynamic language interpreter (Python in this case) will check far more quickly than any code you could ever write. It will simply raise an exception and that's all you need to do. Nothing.

    Should I do it?

    Never test for the right type. You can't -- in general -- do it.

    Let's say you have a function that requires a "number"

    def some_func( x ):
        assert isinstance(x, int)
    

    Bad policy. Your function may work for long or float just as well as int.

    assert instance( x, (int, long, float) )
    

    Bad policy. You've still excluded complex. Indeed, you've also excluded decimal.Decimal and fractions.Rational which are also valid numbers.

    By "type checking" you're going to exclude valid types. The only thing you can do is assume the types are proper and handle the exception gracefully when someone "misuses" your function or class and provides wrong types.

    The most graceful way to handle TypeError?

    Do nothing. The program should totally crash.