Last active
July 21, 2024 22:34
-
-
Save mara004/beb77357102bb78b286c9955c2d1de2e to your computer and use it in GitHub Desktop.
Argparse compat extensions
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
# SPDX-FileCopyrightText: 2024 geisserml <[email protected]> | |
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause | |
import sys | |
import argparse | |
if sys.version_info >= (3, 9): | |
from argparse import BooleanOptionalAction | |
else: | |
# backport, adapted from argparse sources | |
class BooleanOptionalAction (argparse.Action): | |
def __init__(self, option_strings, dest, **kwargs): | |
_option_strings = [] | |
for option_string in option_strings: | |
_option_strings.append(option_string) | |
if option_string.startswith('--'): | |
option_string = '--no-' + option_string[2:] | |
_option_strings.append(option_string) | |
super().__init__(option_strings=_option_strings, dest=dest, nargs=0, **kwargs) | |
def __call__(self, parser, namespace, values, option_string=None): | |
if option_string in self.option_strings: | |
setattr(namespace, self.dest, not option_string.startswith('--no-')) | |
def format_usage(self): | |
return ' | '.join(self.option_strings) | |
if sys.version_info < (3, 8): | |
class ExtendAction (argparse.Action): | |
def __call__(self, parser, namespace, values, option_string=None): | |
items = getattr(namespace, self.dest) or [] | |
items.extend(values) | |
setattr(namespace, self.dest, items) | |
# then do parser.register('action', 'extend', ExtendAction) on your parser instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment