Skip to content

Instantly share code, notes, and snippets.

@dirn
Last active December 16, 2015 18:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dirn/5478924 to your computer and use it in GitHub Desktop.
Save dirn/5478924 to your computer and use it in GitHub Desktop.
`len()`, old vs new
>>> class A:
... pass
...
>>> class B(object):
... pass
...
>>> class C:
... def __len__(self):
... return 0
...
...
>>> class D(object):
... def __len__(self):
... return 0
...
...
>>> len(A())
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: A instance has no attribute '__len__'
>>> len(B())
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: object of type 'B' has no len()
>>> len(C())
0
>>> len(D())
0
>>> try:
... len(A())
... except (TypeError, AttributeError):
... print 'A has no length'
...
...
A has no length
>>> try:
... len(B())
... except (TypeError, AttributeError):
... print 'B has no length'
...
...
B has no length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment