Should I force Python type checking?

前端 未结 7 1938
一个人的身影
一个人的身影 2020-12-09 04:56

Perhaps as a remnant of my days with a strongly-typed language (Java), I often find myself writing functions and then forcing type checks. For example:

def o         


        
相关标签:
7条回答
  • 2020-12-09 05:58

    I agree with Steve's approach when you need to do type checking. I don't often find the need to do type checking in Python, but there is at least one situation where I do. That is where not checking the type could return an incorrect answer that will cause an error later in computation. These kinds of errors can be difficult to track down, and I've experienced them a number of times in Python. Like you, I learned Java first, and didn't have to deal with them often.

    Let's say you had a simple function that expects an array and returns the first element.

    def func(arr): return arr[0]
    

    if you call it with an array, you will get the first element of the array.

    >>> func([1,2,3])
    1
    

    You will also get a response if you call it with a string or an object of any class that implements the getitem magic method.

    >>> func("123")
    '1'
    

    This would give you a response, but in this case it's of the wrong type. This can happen with objects that have the same method signature. You may not discover the error until much later in computation. If you do experience this in your own code, it usually means that there was an error in prior computation, but having the check there would catch it earlier. However, if you're writing a python package for others, it's probably something you should consider regardless.

    You should not incur a large performance penalty for the check, but it will make your code more difficult to read, which is a big thing in the Python world.

    0 讨论(0)
提交回复
热议问题