My Python annoyances

Alex Martelli aleax at mac.com
Fri May 4 10:55:25 EDT 2007


Ben Collver <collver at peak.org> wrote:

> Chris Mellon wrote:
> > You should "check" for the methods by calling them. If the object
> > doesn't support the method in question, you will get a runtime
> > exception. Premature inspection of an object is rarely useful and
> > often outright harmful.
> 
> That makes sense, thank you for the response.
> 
> What about the case where I have an array of objects that represent some
> particular binary file format.  If the object is a file, then I want to
> copy its contents.  If the object is a string, then I want to write the
> string.  And so forth.

"Type-switching" in this way is a rather dubious practice in any
language (it can't respect the "open-closed" principle).  Can't you have
those objects wrapped in suitable wrappers with a "copyorwrite" method
that knows what to do?  For example, StringIO.StringIO is a standard
library wrapper type that makes a string look like a file.

It's a reasonable request you can make to whatever code is putting stuff
in that container: make the container "weakly homogeneous" by having it
stuffed only with "suitably file-like" objects.  Dealing with totally
and weirdly heterogeneous containers is not a sensible task, because
there will be infinite types that COULD be in the container and about
which your code just can't be expected to guess right what to do.


Alex



More information about the Python-list mailing list