type error on porting outfile.write

Eric McCoy ctr2sprt at comcast.net
Thu Dec 22 01:11:01 CET 2005


Dave Hansen wrote:
> or even (closer to the original code)
> 
>    outfile.write(str(object.id)+", ")

That was going to be my suggestion too, but that can mask the underlying
bug since a lot of types have __str__ methods.  Not only could those
types theoretically return a valid stringified integer by coincidence,
if they don't you know nothing except "something went wrong."  Getting a
TypeError would be much more useful for tracking down the bug.

Basically it would be shorthand for:

  assert(isinstance(object.id, int))
  outfile.write(str(object.id) + ", ")

Although I guess in his case, where the bug may be in a library over
which he has no control, it would be better to do:

  assert(isinstance(object.id, int) or isinstance(object.id, str))
  outfile.write("%s, " % (object.id))

since that code will run unmodified on both platforms he's using and
still give him error checking.




More information about the Python-list mailing list