Casting to a "number" (both int and float)?

Laura Creighton lac at openend.se
Fri Aug 28 01:59:05 EDT 2015


I suspect your code will have these 2 lines in it somewhere ...

if isinstance(field, dict):
   return int(field['floatApprox'])

using isinstance() or type() is generally frowned upon because
it breaks duck typing, and makes it necessary for you to write more
code every time somebody wants to feed your code slightly different
arguments.  Your code breaks for no particularly good reason.

But that's not your problem here.  You are parsing things.  And right
now it is your job to know exactly what type things are -- that _is_
the job.  Should somebody start feeding you field['Money'] you don't
want things to quietly assume that pretending it is a float will work,
when you really want a Decimal -- raising a TypeError about 'I don't
recognise this type' is probably what you want to do here.

Laura



More information about the Python-list mailing list