Coverage for rta_to_lstchain_formator/utils/rta_argparse.py: 80%

16 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2024-12-25 05:21 +0000

1import argparse 

2from enum import Enum 

3from typing import Any 

4 

5 

6class EnumAction(argparse.Action): 

7 """Argparse action for handling Enums 

8 

9 Allows to show help with the enum values as choices, while returning an Enum value 

10 once the argument is parsed. 

11 

12 The implementation is copied from this answer on slackoverflow: https://stackoverflow.com/a/60750535 

13 

14 Examples 

15 -------- 

16 >>> class MyEnum(Enum): 

17 >>> Foo = "foo" 

18 >>> Bar = "bar" 

19 >>> parser = argparse.ArgumentParser() 

20 >>> parser.add_argument('--my_enum', type=MyEnum, action=EnumAction) 

21 >>> parser.print_help() # prints --my_enum {foo,bar} 

22 """ 

23 

24 def __init__(self, **kwargs): 

25 # Pop off the enum type from kwargs 

26 enum_type = kwargs.pop("type", None) 

27 

28 # Ensure an Enum subclass is provided 

29 if enum_type is None: 29 ↛ 30line 29 didn't jump to line 30 because the condition on line 29 was never true

30 raise ValueError("Argument `type` must be assigned to an Enum class when using EnumAction. It is not set.") 

31 if not issubclass(enum_type, Enum): 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true

32 raise TypeError( 

33 "Argument `type` must be an Enum class when the action is `EnumAction`, got type {}".format( 

34 str(type(enum_type)) 

35 ) 

36 ) 

37 

38 # Generate choices from the Enum values 

39 kwargs.setdefault("choices", tuple(e.value for e in enum_type)) 

40 

41 # init the action 

42 super(EnumAction, self).__init__(**kwargs) 

43 

44 # keep the enum type to generate Enum instances from their values when called 

45 self.enum = enum_type 

46 

47 def __call__( 

48 self, parser: argparse.ArgumentParser, namespace: argparse.Namespace, values: Any, option_string: str = None 

49 ): 

50 """Convert value back into a `self._enum` instance 

51 

52 Parameters 

53 ---------- 

54 parser : argparse.ArgumentParser 

55 The parser instance invoking this action 

56 namespace : argparse.Namespace 

57 The namespace object that will be returned by the parser. 

58 values : str 

59 The command line argument string 

60 option_string : str, optional 

61 The option string that was used to invoke this action, by default None 

62 """ 

63 # Convert the value back to an enum instance and set it in the namespace 

64 value = self.enum(values) 

65 setattr(namespace, self.dest, value)