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


Groups > comp.lang.python > #80863

Re: isiter builtin

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: isiter builtin
Date 2014-11-16 19:23 +1100
References <CALW7ahx-7JqxWANNX=JpNFqc0rEghDNMa2kMNiHUYaNzR5WgPw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.15876.1416126228.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web