File size: 1,107 Bytes
71687cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Replacements for parts of the toolz library."""

from __future__ import annotations

import collections
import itertools
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Generator, Sequence
    from typing import Any


def groupby_to_dict(keyfunc, sequence):
    """A `toolz`-style groupby implementation.

    Returns a dictionary of { key: [group] } instead of iterators.
    """
    result = collections.defaultdict(list)
    for key, group in itertools.groupby(sequence, keyfunc):
        result[key].extend(group)
    return dict(result)


def unique(sequence: Sequence[Any]) -> Generator[Any, None, None]:
    """A `toolz` inspired `unique` implementation.

    Returns a generator of unique elements in the sequence
    """
    seen: set[Any] = set()
    yield from (
        # seen.add always returns None so we will always return element
        seen.add(element) or element
        for element in sequence
        # only pass along novel elements
        if element not in seen
    )