[Python-ideas] Optional kwarg making attrgetter & itemgetter always return a tuple
masklinn at masklinn.net
Fri Sep 14 09:43:38 CEST 2012
On 2012-09-14, at 03:20 , Steven D'Aprano wrote:
>> This means such code, for instance code "slicing" a matrix of some sort
>> to get only some columns and getting the slicing information from its
>> caller (in situation where extracting a single column may be perfectly
>> sensible) will have to implement a manual dispatch between a "manual"
>> getitem (or getattr) and an itemgetter (resp. attrgetter) call, e.g.
>> slicer = (operator.itemgetter(*indices) if len(indices)> 1
>> else lambda ar: [ar[indices])
> Why is this a problem?
Because it adds significant complexity to the code, and that's for the
trivial version of itemgetter, attrgetter also does keypath resolution
so the code is nowhere near this simple.
It's also anything but obvious what this snippet does on its own.
> If you don't like writing this out in place, write
> it once in a helper function. Not every short code snippet needs to be in
> the standard library.
It's not really "every short code snippet" in this case, it's a way to
avoid a sometimes deleterious special case and irregularity of the stdlib.
>> This makes for more verbose and less straightforward code, I think it
>> would be useful to such situations if attrgetter and itemgetter could be
>> forced into always returning a tuple by way of an optional argument:
> There is no need to add extra complexity to itemgetter and attrgetter for
> something best solved in your code.
I don't agree with this statement, the stdlib flag adds very little
extra complexity, way less than the original irregularity/special case
and way less than necessary to do it outside the stdlib. Furthermore, it
makes the solution (to having a regular output behavior for
(attr|item)getter) far more obvious and makes the code itself much simpler
More information about the Python-ideas