Skip to content

feat: add Enum support with cleaner help message #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion tap/tap.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from argparse import ArgumentParser, ArgumentTypeError
from collections import OrderedDict
from copy import deepcopy
from enum import Enum
from functools import partial
from inspect import isclass
import json
from pathlib import Path
from pprint import pformat
Expand Down Expand Up @@ -156,7 +158,7 @@ def _add_argument(self, *name_or_flags, **kwargs) -> None:
kwargs['help'] = '('

# Type
if variable in self._annotations:
if variable in self._annotations and not self._inherit_enum(variable):
kwargs['help'] += type_to_str(self._annotations[variable]) + ', '

# Required/default
Expand Down Expand Up @@ -270,6 +272,10 @@ def _add_argument(self, *name_or_flags, **kwargs) -> None:
elif kwargs.get('action') not in {'count', 'append_const'}:
kwargs['type'] = var_type

# If inherited from Enum
if self._inherit_enum(variable):
kwargs['choices'] = [enum.value for enum in var_type]

if self._underscores_to_dashes:
# Replace "_" with "-" for arguments that aren't positional
name_or_flags = tuple(name_or_flag.replace('_', '-') if name_or_flag.startswith('-') else name_or_flag
Expand Down Expand Up @@ -702,6 +708,17 @@ def _load_from_config_files(self, config_files: Optional[List[str]]) -> List[str

return args_from_config

def _inherit_enum(self, variable: str) -> bool:
"""Return if the variable inherit from an Enum or not

:param variable: The name of the argument
:return: True if it inherit Enum, False otherwise"""
if variable not in self._annotations:
return False

var_type = self._annotations[variable]
return isclass(var_type) and issubclass(var_type, Enum)

def __str__(self) -> str:
"""Returns a string representation of self.

Expand Down