source: utilitiespy/tudelft/utilities/tools/enum.py

Last change on this file was 1179, checked in by wouter, 4 weeks ago

#371 added enum base class

File size: 885 bytes
Line 
1
2
3from typing import List, TypeVar, Type,cast
4
5T=TypeVar("T",bound=Type)
6
7def enumValues(claz:T)->List[T]:
8 '''
9 @param claz the class of which the enum values are needed
10 @returns the enum values in given clazz T.
11 Assumption : T contains some objects of type T and these are the enum values of T.
12 '''
13 values:List[T] = [getattr(claz, nm) for nm in dir(claz)]
14 return [val for val in values if isinstance(val, claz)]
15
16
17def enumToString(item:T) -> str:
18 '''
19 @param an enum element.
20 @return a string S containing the name of this element.
21 S is such that getattr(item, S) = item.
22 Assumption : enum types T contain some objects of type T and these are the enum values of T.
23 '''
24 return [name for name in dir(type(item)) if getattr(type(item), name)==item][0]
25
26
27class enum:
28 def __repr__(self)->str:
29 return enumToString(self) #type:ignore
Note: See TracBrowser for help on using the repository browser.