codekingpro/portable-devtools
114k
1# Copyright 2009-2024 Joshua Bronson. All rights reserved.2#3# This Source Code Form is subject to the terms of the Mozilla Public4# License, v. 2.0. If a copy of the MPL was not distributed with this5# file, You can obtain one at http://mozilla.org/MPL/2.0/.6 7 8"""Functions for iterating over items in a mapping."""9 10from __future__ import annotations11 12import typing as t13from operator import itemgetter14 15from ._typing import KT16from ._typing import VT17from ._typing import ItemsIter18from ._typing import Maplike19from ._typing import MapOrItems20 21 22def iteritems(arg: MapOrItems[KT, VT] = (), /, **kw: VT) -> ItemsIter[KT, VT]:23 """Yield the items from *arg* and *kw* in the order given."""24 if isinstance(arg, t.Mapping):25 yield from arg.items()26 elif isinstance(arg, Maplike):27 yield from ((k, arg[k]) for k in arg.keys())28 else:29 yield from arg30 yield from t.cast(ItemsIter[KT, VT], kw.items())31 32 33swap: t.Final = itemgetter(1, 0)34 35 36def inverted(arg: MapOrItems[KT, VT]) -> ItemsIter[VT, KT]:37 """Yield the inverse items of the provided object.38 39 If *arg* has a :func:`callable` ``__inverted__`` attribute,40 return the result of calling it.41 42 Otherwise, return an iterator over the items in `arg`,43 inverting each item on the fly.44 45 *See also* :attr:`bidict.BidirectionalMapping.__inverted__`46 """47 invattr = getattr(arg, '__inverted__', None)48 if callable(invattr):49 inv: ItemsIter[VT, KT] = invattr()50 return inv51 return map(swap, iteritems(arg))52 