isiter builtin

Ben Finney ben+python at benfinney.id.au
Sun Nov 16 03:23:36 EST 2014


Garrett Berg <googberg at gmail.com> writes:

> However, there are times when I want to do type checking, and the
> builtin function *isinstance* is of great use.

I would advise that when you think you want type checking, you are
probably being overly restrictive.

> However, this function fails to be satisfactory in returning whether
> the object is a valid iterator. The call hasattr(obj, '__iter__') also
> fails because str and bytes types both have that

Yes, because both ‘str’ and ‘bytes’ objects are valid iterables.


Using ‘isinstance’ in particular is a code smell: it breaks duck typing
(checking not for the object's type, but for how the object behaves,
which is usually what matters) and is almost always the wrong choice.

Not *always* the wrong choice, which is why it's provided, and which is
why I call it a code smell: a strong but not infallible sign something
is wrong with the code as written.

When you reach for ‘isinstance’ (LBYL, which is un-Pythonic), instead
ask yourself: ignoring what type this object is, how do I want it to
behave, and should I just use it in the expectation that it will raise
an exception if it doesn't support that (EAFP, which is very Pythonic)?

-- 
 \     “What is needed is not the will to believe but the will to find |
  `\       out, which is the exact opposite.” —Bertrand Russell, _Free |
_o__)                           Thought and Official Propaganda_, 1928 |
Ben Finney




More information about the Python-list mailing list