[BangPypers] Truth Tests (bool)

Sreenivas Reddy T thatiparthysreenivas at gmail.com
Fri Jan 13 17:13:58 CET 2012


I would like to clear things here.I am assuming beginner as  a common
denominator to this post.

len() method is  just a shortcut to __len__ magic method .So when you  call
len() on your own container type ,it does not traverse whole sequence ,it
just calls __len__ method and returns value(assume self.size=0 in
constructor) from this method.This value incremented or decremented in  add
and remove method on your container type.

Moreover,there can never be length method on iterators - (generators are
also iterators,not vice versa).Iterators are meant for traversing a
sequence or container,they do not keep track of length..generators are
meant to produce infinite items.

When you call len(list) or len(deque) or any collection type,they override
this __len__ internally or some other similar mechanism .That is very much
“similar” to ArrayList here in java.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java

the same can be seen here ..

http://hg.python.org/cpython/file/ba975c7c33d3/Modules/_collectionsmodule.c

To make your type iterable ,you just have to implement __iter__ and next()
method,there is  no __len__ method here.So you will always receive " there
is no len() method your object method".Since you passed generator object to
it.you received that error.

This whole discussion is equal to IEnumerable<T> and ICollection<T> in C#.

python gist is here ,https://gist.github.com/1607183

anybody can test it.

Thanks & Regards,
Sreenivas Reddy Thatiparthy,
9703888668.

"Anyone who has never made a mistake has never tried anything new !!! "
--Albert Einstein


More information about the BangPypers mailing list