-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
54dab05
commit 7588a43
Showing
4 changed files
with
376 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
"""Custom argparse action classes.""" | ||
|
||
from __future__ import annotations | ||
|
||
import typing as t | ||
|
||
from argparse import Action | ||
from enum import Enum | ||
|
||
|
||
# https://docs.python.org/3/library/argparse.html#action-classes | ||
class ArgparseActionEnum(Action): | ||
"""Custom argparse action for Enums.""" | ||
|
||
def __init__( | ||
self, | ||
choices: t.Sequence[str] | None = None, | ||
type: t.Any | None = None, # noqa: A002 | ||
**kwargs, # noqa: ANN003 | ||
) -> None: | ||
enum: t.Any | None = type | ||
if enum is None: | ||
err_msg = "The enum must be provided as argument 'type'." | ||
raise TypeError(err_msg) | ||
if not issubclass(enum, Enum): | ||
err_msg = f"The argument type must be an Enum. The type was {enum}" | ||
raise TypeError(err_msg) | ||
|
||
self._enum = enum | ||
|
||
choices = choices or tuple(enum_type.value for enum_type in self._enum) | ||
|
||
super().__init__(choices=choices, **kwargs) | ||
|
||
def __call__( # noqa: ANN204, D102 | ||
self, | ||
_parser, | ||
namespace: t.Any, | ||
values: str | t.Sequence[t.Any], | ||
_option_string: str | None = None, | ||
): | ||
value = self._enum(values) | ||
setattr(namespace, self.dest, value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.