Advertisement
HasteBin0

Python Generator of a frozenset(),frozendict() fron Enum and key-value iterable

Sep 13th, 2023 (edited)
1,083
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.38 KB | Software | 0 0
  1. frozen_pair_source_t = TypeVar('frozen_pair_source_t', bound = Enum)
  2. frozen_pair_output_t = TypeVar('frozen_pair_output_t')
  3. frozen_pair_return_t = NewType('frozen_pair_return_t', Tuple[FrozenSet[frozen_pair_source_t], Mapping[frozen_pair_source_t, frozen_pair_output_t]])
  4. frozen_pair_key_value_t = NewType('frozen_pair_key_value_t', Tuple[frozen_pair_source_t, frozen_pair_output_t])
  5.  
  6.  
  7.  
  8. def gen_frozen_set_dict_pair(source_enum: Type[frozen_pair_source_t], key_value_pairs: Iterable[frozen_pair_key_value_t], converge_keys: bool, converge_values: bool,
  9.                              finalize_value_entry: Callable[[frozen_pair_source_t, Iterable[frozen_pair_output_t]], frozen_pair_output_t] = None,
  10.                              finalize_key_entry: Callable[[frozen_pair_output_t, Iterable[frozen_pair_source_t]], frozen_pair_source_t] = None) -> frozen_pair_return_t:
  11.     """Generate a frozen set and a frozen dictionary based on the provided input parameters.
  12.  
  13.       Parameters:
  14.       - source_enum (Type[frozen_pair_source_t]): The type of the source enum. This defines the valid keys for the resulting dictionary.
  15.       - key_value_pairs (Iterable[frozen_pair_key_value_t]): An iterable containing key-value pairs. Each pair is a tuple containing a source enum value and an output value.
  16.       - converge_keys (bool): If set to True, the function will converge the keys. This means that for each key in the source enum, the function will associate/link the key itself to its associated values in the dictionary, mapping them to it.
  17.       - converge_values (bool): If set to True, the function will converge the values. This means that for each value associated with a key, the function will associate the value itself to its associated keys in the dictionary, mapping them to it.
  18.       - finalize_value_entry (Callable): An optional function that finalizes the value entry. It takes a key and an iterable of its associated values and returns the finalized value for that key.
  19.       - finalize_key_entry (Callable): An optional function that finalizes the key entry. It takes a value and an iterable of its associated keys and returns the finalized key for that value.
  20.  
  21.       Logic:
  22.       1. Convert the parts iterable into a tuple.
  23.       2. Filter out valid parts from the tuple based on the source enum.
  24.       3. Initialize a dictionary to store the relationships between keys and values.
  25.       4. Populate the dictionary based on the filtered parts.
  26.       5. If converge_keys is True, converge the keys.
  27.       6. If converge_values is True, converge the values.
  28.       7. Finalize the value entries using the provided finalize_value_entry function.
  29.       8. Finalize the key entries using the provided finalize_key_entry function.
  30.       9. Return a frozen set of keys and a frozen dictionary.
  31.  
  32.       Returns:
  33.       - frozen_pair_return_t: A tuple containing a frozen set of keys and a frozen dictionary.
  34.  
  35.       Usage:
  36.       ```python3
  37.       class SampleEnum(Enum):
  38.           A = "A"
  39.           B = "B"
  40.  
  41.       # Use the function
  42.       frozen_set, frozen_dict = gen_frozen_set_dict_pair(SampleEnum, [("A", "X"), ("B", "Y")], True, True)
  43.       ```
  44.  
  45.       Suggested Use Cases:
  46.       - When you need to create an immutable mapping between a set of keys and values and want the flexibility to converge keys and values.
  47.       - In scenarios where you want to ensure type safety and clarity in the function's expected inputs and outputs using type annotations.
  48.       - When working with data that should not be modified after its creation, ensuring data integrity.
  49.   """
  50.     net_of_parts: Tuple[frozen_pair_key_value_t, ...] = tuple(x_part for x_part in key_value_pairs if isinstance(x_part, tuple) and len(x_part) == 2 and x_part[0] in source_enum)
  51.     build_table: Dict[frozen_pair_source_t, Deque[frozen_pair_output_t]] = defaultdict(deque)
  52.     for key, value in net_of_parts:
  53.         build_table[key].append(value)
  54.     set_of_a_keys: Set[frozen_pair_source_t] = set(key for key, _ in net_of_parts)
  55.     set_of_b_keys: Set[frozen_pair_output_t] = set(value for _, value in net_of_parts)
  56.     if converge_keys:
  57.         for key in set_of_a_keys:
  58.             for vx in build_table[key]:
  59.                 build_table[vx].append(key)
  60.     if converge_values:
  61.         for value in set_of_b_keys:
  62.             for kx in build_table[value]:
  63.                 build_table[kx].append(value)
  64.     if finalize_value_entry is None:
  65.         for key in set_of_a_keys:
  66.             value_queue = build_table[key]
  67.             if len(value_queue) == 1:
  68.                 build_table[key] = value_queue.pop()
  69.             elif len(value_queue) > 1:
  70.                 build_table[key] = tuple(value_queue)
  71.             else:
  72.                 del build_table[key]
  73.     else:
  74.         for key in set_of_a_keys:
  75.             build_table[key] = finalize_value_entry(key, iter(build_table[key]))
  76.     if finalize_key_entry is None:
  77.         for value in set_of_b_keys:
  78.             key_queue = build_table[value]
  79.             if len(key_queue) == 1:
  80.                 build_table[value] = key_queue.pop()
  81.             elif len(key_queue) > 1:
  82.                 build_table[value] = tuple(key_queue)
  83.             else:
  84.                 del build_table[value]
  85.     else:
  86.         for value in set_of_b_keys:
  87.             build_table[value] = finalize_value_entry(value, iter(build_table[value]))
  88.     return frozenset(set_of_a_keys), frozendict(build_table)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement