Last active
December 16, 2015 18:39
-
-
Save dirn/5478924 to your computer and use it in GitHub Desktop.
`len()`, old vs new
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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