Recursive list comprehension

  • Thread starter Timothy Babytch
  • Start date
S

Steven Bethard

Terry said:
This is a ways off, if ever, but I think the general advice for user code
is to use the newer protocol.

Yes, definitely. I hope no one misconstrued me to be suggesting that
you should use the 'sequence protocol' for iterators (e.g. using
__getitem__ and raising an IndexError). This is deprecated and is only
supported for backwards compatiblity. All new code should define
__iter__ instead.
So, for the purpose of writing new code, I
think it justified to forget about or at least ignore the older iteration
protocol.

This is probably valid as long as you don't need your code to work with
any objects defined before the __iter__ protocol.

Steve
 
N

Nick Craig-Wood

Peter Otten said:
While trying to break your code with a len() > 1 string I noted that strings
don't feature an __iter__ attribute. Therefore obj.__iter__() is not
equivalent to iter(obj) for strings. Do you (plural) know whether this is a
CPython implementation accident or can be relied upon?

I'd like to know this too!

You can write the above as the shorter (and safer IMHO - it doesn't
catch any exceptions it shouldn't)

def flatten( i ):
if hasattr(i, "__iter__"):
for j in i:
for k in flatten(j):
yield k
else:
yield i
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,213
Messages
2,571,108
Members
47,700
Latest member
Naveed baloch

Latest Threads

Top