The Voidspace Techie Blog

Gravatar Another problem with the "better to ask forgiveness" example is that it could very well hide a bug inside the implementation of methodname() which raises an AttributeError.


Gravatar Hi,
In your statement:

"There is another idiom that is often advocated in Python; the use of exceptions for duck typing. Where you have a code path receiving an object that may be one of several types you often want to handle different objects in different ways. Rather than do strict type checking with isinstance it is more idiomatic in Python to base how you use objects on what operations they support - this is the essence of duck typing"

So, the central idea of duck typing is when a function or method is able to accept different object types, not related by type hierarchy, and perform analogous operations with them without further modification to the method/function. You know, using file-like objects in code written to accept files.

This duck typing is hampered if the function checks for type.

If a function needs to check whether an argument is a file or a string, then the duck typing would allow a sufficiently file like object to be processed as a file and a sufficiently string-like object to be processed as a string. In this case you are going to be stumped when you have a stringfile or filestring object that combines aspects of both, either by its methods and/or by accepting both a string and a file ABC. A possible solution is to create an intermediate object that for calls to the function in question, hides sufficient functionality for the argument to be classed as one or the other.

There's no substitute for reading the code it seems

- Paddy.


Gravatar Maybe if «try: ... except:» had been spelt «try: ... handle:» or «try: ... catch"» then people wouldn't get so hung up about it.

«try: thing ... handle: SomeException ...» reads better too.


Gravatar @David
Even if you changed the keyword I would still object to abusing exception handling.


Gravatar Oh sure, I wasn't meaning to imply that you were hung up about it, from the blog article your attitude seems very mature and sensible.

Really I meant the unwashed C++ masses who cringe when you explain that the iterator protocol uses an exception called StopIteration.


Name:

Email:

URL:

Comment:  ? 

 

Commenting by HaloScan