[Python-Dev] basenumber redux (original) (raw)

Jason Orendorff jason.orendorff at gmail.com
Wed Jan 18 21:02:22 CET 2006


On 1/17/06, "Martin v. Löwis" <martin at v.loewis.de> wrote:

Alex Martelli wrote: > But this doesn't apply to the Python Standard Library, for example see > line 1348 of imaplib.py: "if isinstance(datetime, (int, float)):". [...] > Being able to change imaplib to use basenumber instead of (int, float) > won't make it SIMPLER, but it will surely make it BETTER -- why should > a long be rejected, or a Decimal, for that matter?

Right. I think this function should read _if isinstance(datetime, str) and _ (datetime[0],datetime[-1]) == ('"','"'): return datetime # Assume in correct format if isinstance(datetime, (tuple, time.structtime)): tt = datetime else: tt = time.localtime(datetime)

So... arbitrary number-like objects should work, but arbitrary sequence-like objects should fail? Hmmm. Maybe that "if isinstance()" line should say "if hasattr(date_time, 'getitem'):". Am I sure? No. The original author of imaplib apparently got it wrong, and Martin got it wrong, and they're both smarter than me.

Really this is just further proof that type-checking is a royal pain in Python. Or rather, it's not hard to cover the builtin and stdlib types, but it's hard to support "duck typing" too. Are we going about this the right way? Options:

  1. Redesign the API so each parameter has a clearly defined set of operations it must support, thus eliminating the need for type-checking. Drawback: An annoying API might be worse than the problem we're trying to solve.

  2. Write a set of imprecise, general-purpose type-checking functions (is_real_number(v), is_sequence(v), ...) and use those. (They are imprecise because the requirements are vague and because it's not really possible to pin them down.) Drawback: Error-prone, compounded by deceptively clean appearance.

  3. Write very specific custom type-checking code each time you need it (the imaplib approach). Drawbacks: Error-prone (as we've seen), precarious, tedious, unreadable.

  4. Use the "better-to-ask-forgiveness-than-permission" idiom. Drawback: Potential bad behavior on error, again potentially worse than the original problem.

Yuck. Does anyone have the answer to this one? Or is the problem not as bad as it looks?

-j



More information about the Python-Dev mailing list