Return a callable object that fetches the given attribute(s) from its operand. After f = attrgetter('name'), the call f(r) returns r.name. After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). After h = attrgetter('name.first', 'name.last'), the call h(r)
| 230 | # Generalized Lookup Objects **************************************************# |
| 231 | |
| 232 | class attrgetter: |
| 233 | """ |
| 234 | Return a callable object that fetches the given attribute(s) from its operand. |
| 235 | After f = attrgetter('name'), the call f(r) returns r.name. |
| 236 | After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). |
| 237 | After h = attrgetter('name.first', 'name.last'), the call h(r) returns |
| 238 | (r.name.first, r.name.last). |
| 239 | """ |
| 240 | __slots__ = ('_attrs', '_call') |
| 241 | |
| 242 | def __init__(self, attr, *attrs): |
| 243 | if not attrs: |
| 244 | if not isinstance(attr, str): |
| 245 | raise TypeError('attribute name must be a string') |
| 246 | self._attrs = (attr,) |
| 247 | names = attr.split('.') |
| 248 | def func(obj): |
| 249 | for name in names: |
| 250 | obj = getattr(obj, name) |
| 251 | return obj |
| 252 | self._call = func |
| 253 | else: |
| 254 | self._attrs = (attr,) + attrs |
| 255 | getters = tuple(map(attrgetter, self._attrs)) |
| 256 | def func(obj): |
| 257 | return tuple(getter(obj) for getter in getters) |
| 258 | self._call = func |
| 259 | |
| 260 | def __call__(self, obj): |
| 261 | return self._call(obj) |
| 262 | |
| 263 | def __repr__(self): |
| 264 | return '%s.%s(%s)' % (self.__class__.__module__, |
| 265 | self.__class__.__qualname__, |
| 266 | ', '.join(map(repr, self._attrs))) |
| 267 | |
| 268 | def __reduce__(self): |
| 269 | return self.__class__, self._attrs |
| 270 | |
| 271 | class itemgetter: |
| 272 | """ |
no outgoing calls
no test coverage detected