Skip to content

Commit

Permalink
types/ArgparseEnum: add argtype method
Browse files Browse the repository at this point in the history
Intended to be used as the type converter method for argparse options
that use the enum values as choices.

It raises a custom `argparse.ArgumentTypeError` so that we can provide
a helpful error message that lists all of the valid enum values.
  • Loading branch information
joverlee521 committed Mar 9, 2023
1 parent 9bed714 commit 23f4fdb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion augur/filter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def register_arguments(parser):
output_group.add_argument('--output-log', help="tab-delimited file with one row for each filtered strain and the reason it was filtered. Keyword arguments used for a given filter are reported in JSON format in a `kwargs` column.")
output_group.add_argument(
'--empty-results-reporting',
type=EmptyResultsReportingMethod,
type=EmptyResultsReportingMethod.argtype,
choices=list(EmptyResultsReportingMethod),
default=EmptyResultsReportingMethod.ERROR,
help="How should empty filter results be reported.")
Expand Down
17 changes: 17 additions & 0 deletions augur/types.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from argparse import ArgumentTypeError
import enum


Expand All @@ -19,6 +20,22 @@ def __str__(self) -> str:
"""
return self.value

@classmethod
def argtype(cls, input_string):
"""
Intended to be used as the argument type converter for argparse options
that use the enum values as inputs.
Raises a custom `argparse.ArgumentTypeError` so that the error
message can include a helpful list of the valid enum values.
"""
try:
return cls(input_string)
except ValueError:
choices = ", ".join(map(str, cls))
raise ArgumentTypeError(
f"invalid choice: {input_string!r} (choose from {choices})")


@enum.unique
class DataErrorMethod(ArgparseEnum):
Expand Down

0 comments on commit 23f4fdb

Please sign in to comment.