Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80863 > unrolled thread

Re: isiter builtin

Started byBen Finney <ben+python@benfinney.id.au>
First post2014-11-16 19:23 +1100
Last post2014-11-16 19:23 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: isiter builtin Ben Finney <ben+python@benfinney.id.au> - 2014-11-16 19:23 +1100

#80863 — Re: isiter builtin

FromBen Finney <ben+python@benfinney.id.au>
Date2014-11-16 19:23 +1100
SubjectRe: isiter builtin
Message-ID<mailman.15876.1416126228.18130.python-list@python.org>
Garrett Berg <googberg@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web