PyCon: Evangelizing Python
Posted Mar 31, 2013 9:48 UTC (Sun) by dark
In reply to: PyCon: Evangelizing Python
Parent article: PyCon: Evangelizing Python
It's not really about trust. It's about embracing duck typing.
If you're parsing data from strings then by all means check that it's well-formed and that it's the kind of data you expect -- it's all under your control at that point.
If you're accepting a value from elsewhere, then it may make sense to do sanity checks on it, but those should be along the lines of "does it support the methods I expect to call on it", not "does it have the specific type I expect". The best example of this is file objects -- you really shouldn't enforce that it's a "file", you should let the caller pass in whatever file-like object is most convenient.
Most python code is simple enough that you can do those 'checks' just by calling the methods when you need them and getting an exception if they fail. But if you're about to insert such a received value into a complex system and you want to catch errors before they're deep in the stack then it may make sense to inspect the value a bit. Or just convert it -- calling int(value) or str(value) will throw exceptions right away, and the latter will let the value handle its own conversion.
to post comments)