My Python annoyances

Ant antroy at gmail.com
Fri May 4 10:34:32 EDT 2007


On May 4, 3:17 pm, Ben Collver <coll... at peak.org> wrote:
> Chris Mellon wrote:
...
> > Code like this is working directly against Python philosophy. You
> > probably got told this on #python, too. There's hardly any
> > circumstance where you should need to validate the exact class of an
> > object, and as long as they have the same interface theres no harm
> > whatsoever in tempfile changing it's return value between Python
> > versions.
>
> I am unqualified to comment on the Python philosophy, but I would like
> for my function to do some basic error checking on its arguments.  I
> will read up on the Python philosophy.

The basic point here is that the code will do it's own error checking.
If you pass in a string to your function, and it tries to call
write("xxx") on it, then you will get an exception thrown:

AttributeError: 'str' object has no attribute 'write

If your goal is to provide feedback to a potential user that they are
using the wrong arguments, then you can use something like the
following (the "Easier to ask for forgiveness than for permission"
idiom):

>>> arg = "A String not a File"
>>> try:
...   arg.write("")
... except AttributeError:
...   print "You need to pass in a file like object!"
...
You need to pass in a file like object!





More information about the Python-list mailing list