[issue31086] Add namedattrgetter function which acts like attrgetter but uses namedtuple

Isaac Morland report at bugs.python.org
Sun Jul 30 21:21:23 EDT 2017


Isaac Morland added the comment:

Here is the diff.  Note that I assume implementation of #31085, which allows me to push determination of a name for the namedtuple down into namedtuple itself:

diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index 62cf708..d507d23 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -14,7 +14,8 @@ list, set, and tuple.
 
 '''
 
-__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
+__all__ = ['deque', 'defaultdict', 'namedtuple', 'namedattrgetter',
+            'UserDict', 'UserList',
             'UserString', 'Counter', 'OrderedDict', 'ChainMap']
 
 # For backwards compatibility, continue to make the collections ABCs
@@ -23,7 +24,7 @@ from _collections_abc import *
 import _collections_abc
 __all__ += _collections_abc.__all__
 
-from operator import itemgetter as _itemgetter, eq as _eq
+from operator import itemgetter as _itemgetter, attrgetter as _attrgetter, eq as _eq
 from keyword import iskeyword as _iskeyword
 import sys as _sys
 import heapq as _heapq
@@ -451,6 +452,14 @@ def namedtuple(typename, field_names, *, verbose=False, rename=False, module=Non
 
     return result
 
+def namedattrgetter (attr, *attrs):
+    ag = _attrgetter (attr, *attrs)
+
+    if attrs:
+        nt = namedtuple (None, (attr,) + attrs, rename=True)
+        return lambda obj: nt._make (ag (obj))
+    else:
+        return ag
 
 ########################################################################
 ###  Counter

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue31086>
_______________________________________


More information about the Python-bugs-list mailing list