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


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

Re: isiter builtin

Started byPeter Otten <__peter__@web.de>
First post2014-11-16 10:04 +0100
Last post2014-11-16 10:04 +0100
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 Peter Otten <__peter__@web.de> - 2014-11-16 10:04 +0100

#80866 — Re: isiter builtin

FromPeter Otten <__peter__@web.de>
Date2014-11-16 10:04 +0100
SubjectRe: isiter builtin
Message-ID<mailman.15877.1416128673.18130.python-list@python.org>
Garrett Berg wrote:

> I have been working with python for a few years now, and two of my
> favorite features about it are iterators and duck typing. The fact that
> every iterator under the sun can be accessed with a simple for loop is one
> of the most amazing features of python.
> 
> However, there are times when I want to do type checking, and the builtin
> function *isinstance* is of great use. 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, and are rarely what you mean when you are asking if something is an
> iterator (how often have you iterated over a string?)
> 
> I propose a new builtin to address this problem. I have created code for
> it here:
> 
> https://gist.github.com/cloudformdesign/de9b54d30547ddd28ec4

I see no reason not to inline this short function:

> def isiter(obj, exclude=(str, bytes, bytearray)):
>     '''Returns True if object is an iterator.
>     Returns False for str, bytes and bytearray objects
>     by default'''
>     return (False if isinstance(obj, exclude)
>             else True if hasattr(obj, '__iter__')
>             else False)

Why not

      return hasattr(obj, "__iter__") and not isinstance(obj, exclude)

> This will allow simple type checking on an input to determine whether it
> is an iterator.

You mean "iterable".

I'd like to see a few of your use-cases. I think most the time you don't mix 
arbitrary iterables, so to walk a tree like

["alpha", "beta", [3, "delta", ["epsilon", "zeta"]]]

isinstance(obj, list) would be sufficient. Likewise for

["alpha", iter("abc"), ["beta", ["gamma"]]]

isinstance(obj, str) would work.

[toc] | [standalone]


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


csiph-web