Created
September 21, 2021 15:59
-
-
Save Xophmeister/42f56d6d9b7ca52c7078af81d69fd9ea to your computer and use it in GitHub Desktop.
argparse.Action like "store", but with an optional modifier
This file contains hidden or 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
import argparse | |
import sys | |
from enum import Enum | |
class Viewport(Enum): | |
All = "all" | |
WorkingDirectory = "here" | |
OwnedByMe = "mine" | |
# NOTE The property decorator doesn't work on default and choices, | |
# below; probably due to some Enum metaprogramming magic. As such, | |
# we have to make do with methods. | |
@classmethod | |
def default(cls): | |
default, *_ = cls | |
return default | |
@classmethod | |
def choices(cls): | |
return [*cls] | |
class StoreOptionalModifier(argparse.Action): | |
def __call__(self, _parser:argparse.ArgumentParser, namespace:argparse.Namespace, values:Viewport, _option_string:str): | |
setattr(namespace, self.dest, values or Viewport.default()) | |
p = argparse.ArgumentParser() | |
p.add_argument("--view", dest="view", metavar="WHAT", | |
nargs="?", | |
action=StoreOptionalModifier, | |
type=Viewport, | |
choices=Viewport.choices(), | |
default=argparse.SUPPRESS, | |
help="show the recoverable files from WHAT") | |
if __name__ == "__main__": | |
print(p.parse_args(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment