简体   繁体   中英

Duck typing and unhelpful error messages in Python

Consider the following code, which is embedded deep in some module (foo and bar are dicts ).

vals = [foo[key] for key in bar.keys()]

If for some reason bar contained keys that foo did not, this would lead to a KeyError . Let's say that the way the user interacts with this module has nothing to do with foo or bar, but has passed some sort of argument the module author did not foresee that causes this error to be raised. Rather than checking the inputs and disallowing this type/value of input, the author did the Pythonic thing and let this error be thrown.

My question is this: It seems like Python's duck typing can lead to unhelpful error messages such as in this hypothetical case above. Is there a way to author your code such that it throws more helpful error messages? Perhaps you could throw warnings based on type checking / values?

This seems to me to be more a limitation with the list comprehension than a language issue, since list comprehensions sacrifice versatility for conciseness; as such, exceptions cannot be caught in the middle of such an expression. A more detailed error or warning message can be easily reproduced by simply manually iterating, with little to no performance or readability loss:

vals = []
for k in bar.keys():
    # This uses the EAFP paradigm. An alternative is to check for
    # dictionary membership first
    try:
        vals.append(foo[k])
    except KeyError:
        raise SuperUsefulException(str(k))

And since this is clearly supported by the programming language, this is up to the module author.

To be honest, the correct thing to do depends upon the contract for the module. Is it supposed to throw an error in this situation? Is it supposed to silently ignore the condition?

Unfortunately contractual behavior is frequently not specified. The intermediate layer caller should make a decision re: error handling in this case in order to return a useful error message since the top level caller knows nothing of for and bar.

No ducks were harmed in the making of this answer. If fact, none were involved at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM