Skip to content

Instantly share code, notes, and snippets.

@mattmakesmaps
Created December 20, 2013 05:25
Show Gist options
  • Save mattmakesmaps/8050735 to your computer and use it in GitHub Desktop.
Save mattmakesmaps/8050735 to your computer and use it in GitHub Desktop.
An example of the applied duck-type interface within common python built-in functions. The len() built-in will successfully execute on any input that meets its interface criteria: a __len__() method that returns an integer.
Python 2.7.6 (default, Dec 7 2013, 21:06:22)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass(object):
... def __init__(self):
... self.foo = "foo"
...
>>> m = MyClass()
>>> m.foo
'foo'
>>> len(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'MyClass' has no len()
>>> class MyClass(object):
... def __init__(self):
... self.baz = "baz"
... def __len__(self):
... return "I Don't Have A Length!!!"
...
>>> p = MyClass()
>>> p.baz
'baz'
>>> len(p)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> class MyClass(object):
... def __init__(self):
... self.bar = "bar"
... def __len__(self):
... return 35
...
>>> q = MyClass()
>>> q.bar
'bar'
>>> q.baz
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'baz'
>>> len(q)
35
>>> len(p)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> len(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'MyClass' has no len()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment