Initializes enum fields. @param name: name of this field @param default: default value of this field @param enum: either an enum, a dict or a tuple of two callables. Dict keys are the internal values, while the dict valu
(self,
name, # type: str
default, # type: Optional[I]
enum, # type: _EnumType[I]
fmt="H", # type: str
)
| 2519 | |
| 2520 | class _EnumField(Field[Union[List[I], I], I]): |
| 2521 | def __init__(self, |
| 2522 | name, # type: str |
| 2523 | default, # type: Optional[I] |
| 2524 | enum, # type: _EnumType[I] |
| 2525 | fmt="H", # type: str |
| 2526 | ): |
| 2527 | # type: (...) -> None |
| 2528 | """ Initializes enum fields. |
| 2529 | |
| 2530 | @param name: name of this field |
| 2531 | @param default: default value of this field |
| 2532 | @param enum: either an enum, a dict or a tuple of two callables. |
| 2533 | Dict keys are the internal values, while the dict |
| 2534 | values are the user-friendly representations. If the |
| 2535 | tuple is provided, the first callable receives the |
| 2536 | internal value as parameter and returns the |
| 2537 | user-friendly representation and the second callable |
| 2538 | does the converse. The first callable may return None |
| 2539 | to default to a literal string (repr()) representation. |
| 2540 | @param fmt: struct.pack format used to parse and serialize the |
| 2541 | internal value from and to machine representation. |
| 2542 | """ |
| 2543 | if isinstance(enum, ObservableDict): |
| 2544 | cast(ObservableDict, enum).observe(self) |
| 2545 | |
| 2546 | if isinstance(enum, tuple): |
| 2547 | self.i2s_cb = enum[0] # type: Optional[Callable[[I], str]] |
| 2548 | self.s2i_cb = enum[1] # type: Optional[Callable[[str], I]] |
| 2549 | self.i2s = None # type: Optional[Dict[I, str]] |
| 2550 | self.s2i = None # type: Optional[Dict[str, I]] |
| 2551 | elif isinstance(enum, type) and issubclass(enum, Enum): |
| 2552 | # Python's Enum |
| 2553 | i2s = self.i2s = {} |
| 2554 | s2i = self.s2i = {} |
| 2555 | self.i2s_cb = None |
| 2556 | self.s2i_cb = None |
| 2557 | names = [x.name for x in enum] |
| 2558 | for n in names: |
| 2559 | value = enum[n].value |
| 2560 | i2s[value] = n |
| 2561 | s2i[n] = value |
| 2562 | else: |
| 2563 | i2s = self.i2s = {} |
| 2564 | s2i = self.s2i = {} |
| 2565 | self.i2s_cb = None |
| 2566 | self.s2i_cb = None |
| 2567 | keys = [] # type: List[I] |
| 2568 | if isinstance(enum, list): |
| 2569 | keys = list(range(len(enum))) # type: ignore |
| 2570 | elif isinstance(enum, DADict): |
| 2571 | keys = enum.keys() |
| 2572 | else: |
| 2573 | keys = list(enum) # type: ignore |
| 2574 | if any(isinstance(x, str) for x in keys): |
| 2575 | i2s, s2i = s2i, i2s # type: ignore |
| 2576 | for k in keys: |
| 2577 | value = cast(str, enum[k]) # type: ignore |
| 2578 | i2s[k] = value |