[Python-ideas] Optional kwarg making attrgetter & itemgetter always return a tuple
oscar.j.benjamin at gmail.com
Sat Sep 15 13:09:12 CEST 2012
On Sep 14, 2012 10:02 PM, "Jim Jewett" <jimjjewett at gmail.com> wrote:
> On 9/14/12, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> > I can see why you would expect different behaviour here, though. I tend
> > to think of the functions in the operator module as convenience
> > but as *efficient* nameable functions referring to operations that are
> > normally invoked with a non-function syntax. Which is more convenient
> > of the following:
> > 1) using operator
> > import operator
> > result = sorted(values, key=operator.attrgetter('name'))
> I would normally write that as
> from operator import attrgetter as attr
> ... # may use it several times
> result=sorted(values, key=attr('name'))
> which is about the best I could hope for, without being able to use
> the dot itself.
To be clear, I wasn't complaining about the inconvenience of importing and
referring to attrgetter. I was saying that if the obvious alternative
(lambda functions) is at least as convenient then it's odd to describe
itemgetter/attrgetter as convenience functions.
> > 2) using lambda
> > result = sorted(values, key=lambda v: v.name)
> And I honestly think that would be worse, even if lambda didn't have a
> code smell. It focuses attention on the fact that you're creating a
> callable, instead of on the fact that you're grabbing the name
I disagree here. I find the fact that a lambda function shows me the
expression I would normally use to get the quantity I'm interested in makes
it easier for me to read. When I look at it I don't see it as a callable
function but as an expression that I'm passing for use somewhere else.
> > In general it is bad to conflate scalar/sequence semantics so that a
> > should get a different type of object depending on the length of a
> > sequence.
> Yeah, but that can't really be solved well in python, except maybe by
> never extending an API to handle sequences. I would personally not
> consider that an improvement.
> Part of the problem is that the cleanest way to take a variable number
> of arguments is to turn them into a sequence under the covers (*args),
> even if they weren't passed that way.
You can extend an API to support sequences by adding a new entry point.
This is a common idiom in python: think list.append vs list.extend.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas