Should I force Python type checking?

前端 未结 7 1948
一个人的身影
一个人的身影 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:45

    Personally I have an aversion to asserts it seems that the programmer could see trouble coming but couldn't be bothered to think about how to handle them, the other problem is that your example will assert if either parameter is a class derived from the ones you are expecting even though such classes should work! - in your example above I would go for something like:

    def orSearch(d, query):
        """ Description of what your function does INCLUDING parameter types and descriptions """
        result = None
        if not isinstance(d, dict) or not isinstance(query, list):
            print "An Error Message"
            return result
        ...
    

    Note type only matches if the type is exactly as expected, isinstance works for derived classes as well. e.g.:

    >>> class dd(dict):
    ...    def __init__(self):
    ...        pass
    ... 
    >>> d1 = dict()
    >>> d2 = dd()
    >>> type(d1)
    
    >>> type(d2)
    
    >>> type (d1) == dict
    True
    >>> type (d2) == dict
    False
    >>> isinstance(d1, dict)
    True
    >>> isinstance(d2, dict)
    True
    >>> 
    

    You could consider throwing a custom exception rather than an assert. You could even generalise even more by checking that the parameters have the methods that you need.

    BTW It may be finicky of me but I always try to avoid assert in C/C++ on the grounds that if it stays in the code then someone in a few years time will make a change that ought to be caught by it, not test it well enough in debug for that to happen, (or even not test it at all), compile as deliverable, release mode, - which removes all asserts i.e. all the error checking that was done that way and now we have unreliable code and a major headache to find the problems.

提交回复
热议问题