[Python-ideas] get() method for list and tuples

Steven D'Aprano steve at pearwood.info
Tue Feb 28 21:10:34 EST 2017

On Wed, Mar 01, 2017 at 02:26:18AM +0100, Michel Desmoulin wrote:

> The fact the API is not exactly the same doesn't prevent duck typing.
> Duck typing is precesily about incomplete but good enough similar API.

Indeed. But the relationship goes this way:

    # Duck-typing done the right way.

    Types P and Q both quack like ducks, so if all we need is 
    something that quacks, either P or Q will do.

not this way:

    Types P and Q both quack like ducks. I want something that
    swims like a duck, like P. Q doesn't swim at all, so we need
    to add Q.swim() so we can duck-type P or Q.

If we are going to propose Q.swim(), it must be because it makes sense 
for Q instances to swim, regardless of what P does. 

> For the dict and list:
> - you can iterate on both
> - you can index both
> - you can size both

Right -- because all these operations make sense for both dicts and 

Does get() make sense for both? It certainly makes sense for dicts. It 
makes *some* sense for lists, but (in my opinion) not enough to justify 
making it a built-in method of the type.

Making it a built-in method isn't just a convenience, it is also 
blessing this as "the right thing to do". As I've said, in my experience 
trying to index into arbitrary positions of a sequence (list or tuple) 
without knowing whether that index exists or not is rarely the right 
thing to do. (That makes it very different from key lookup in a mapping 
or dict.)

I believe that the way to argue for list.get() is not because it will 
make it easy to duck-type lists and dicts. It is (in my experience) very 
rare to need to duck-type lists and dicts. I believe you should identify 
code that handles lists that would benefit from this change.

Under what circumstances do you ask for the 17th item of a list which 
may only contain 9 items? (For arbitrary values of 17 and 9.)


More information about the Python-ideas mailing list