Skip to main content

python argparse best practice.

Project description

argparse-best-practice

def best_practice_bool() -> None:
    def default_false() -> None:
        parser = ArgumentParser()
        parser.add_argument('--default-false', action=BooleanOptionalAction, default=False)
        parser.add_argument('--default-false-exist', action=BooleanOptionalAction, default=False)
        parser.add_argument('--default-false-exist-with-no', action=BooleanOptionalAction, default=False)
        args = parser.parse_args(['--default-false-exist',
                                  '--no-default-false-exist-with-no'
                                  ])
        assert args.default_false == False
        assert args.default_false_exist == True
        assert args.default_false_exist_with_no == False
    default_false()


    def default_true() -> None:
        parser = ArgumentParser()
        parser.add_argument('--default-true', action=BooleanOptionalAction, default=True)
        parser.add_argument('--default-true-exist', action=BooleanOptionalAction, default=True)
        parser.add_argument('--default-true-exist-with-no', action=BooleanOptionalAction, default=True)
        args = parser.parse_args(['--default-true-exist',
                                  '--no-default-true-exist-with-no'
                                  ])
        assert args.default_true == True
        assert args.default_true_exist == True
        assert args.default_true_exist_with_no == False
    default_true()


def best_practice_string() -> None:
    def default_string() -> None:
        parser = ArgumentParser()
        parser.add_argument('--default-string', default='a')
        parser.add_argument('--default-string-exist', default='a')
        args = parser.parse_args(['--default-string-exist', 'b'])
        assert args.default_string == 'a'
        assert args.default_string_exist == 'b'
    default_string()


    def my_string_validation() -> None:
        class MyStringValidationError(Exception):
            def __init__(self, value: str) -> None:
                self.value = value
                super().__init__()


        class MyStringValidator(Action):
            def __call__(self, 
                         parser: ArgumentParser, 
                         namespace: Namespace, 
                         values: Union[Text, Sequence[Any], None], 
                         option_string: Optional[Text]) -> None:
                if values.islower():
                    raise MyStringValidationError(values)
                setattr(namespace, self.dest, values)


        parser = ArgumentParser()
        parser.add_argument('--my-string-validation', action=MyStringValidator)
        try:
            args = parser.parse_args(['--my-string-validation', 'a'])
        except MyStringValidationError as e:
            assert MyStringValidationError('a').value == e.value
        else:
            assert False
        args = parser.parse_args(['--my-string-validation', 'A'])
        assert args.my_string_validation == 'A'
    my_string_validation()


def best_practice_number() -> None:
    def default_number() -> None:
        parser = ArgumentParser()
        parser.add_argument('--default-number', type=int, default=0)
        parser.add_argument('--default-number-exist', type=int, default=0)
        args = parser.parse_args(['--default-number-exist', '1'])
        assert args.default_number == 0
        assert args.default_number_exist == 1
    default_number()


    def my_number_validation() -> None:
        class MyNumberValidationError(Exception):
            def __init__(self, value: int) -> None:
                self.value = value
                super().__init__()


        class MyNumberValidator(Action):
            def __call__(self, 
                         parser: ArgumentParser, 
                         namespace: Namespace, 
                         values: Union[Text, Sequence[Any], None], 
                         option_string: Optional[Text]) -> None:
                if 0 > values:
                    raise MyNumberValidationError(values)
                setattr(namespace, self.dest, values)


        parser = ArgumentParser()
        parser.add_argument('--my-number-validation', action=MyNumberValidator, type=int, default=0)
        try:
            args = parser.parse_args(['--my-number-validation', '-1'])
        except MyNumberValidationError as e:
            assert MyNumberValidationError(-1).value == e.value
        else:
            assert False
    my_number_validation()


def best_practice_list() -> None:
    def default_empty_list() -> None:
        parser = ArgumentParser()
        parser.add_argument('--default-empty-list', action='extend', nargs='+', default=[])
        parser.add_argument('--default-empty-list-exist', action='extend', nargs='+', default=[])
        args = parser.parse_args(['--default-empty-list-exist', 'a', 'b'])
        assert args.default_empty_list == []
        assert args.default_empty_list_exist == ['a', 'b']
    default_empty_list()


    def my_unique_list() -> None:
        class MyUniqueListCreator(Action):
            def __call__(self, 
                         parser: ArgumentParser, 
                         namespace: Namespace, 
                         values: Union[Text, Sequence[Any], None], 
                         option_string: Optional[Text]) -> None:
                default = getattr(namespace, self.dest) if hasattr(namespace, self.dest) else []
                default.extend(values)      
                new_value = list(set(default))
                new_value.sort()      
                setattr(namespace, self.dest,  new_value)


        parser = ArgumentParser()    
        parser.add_argument('--my-unique-list', action=MyUniqueListCreator, nargs='+', default=['a'])
        args = parser.parse_args(['--my-unique-list', 'a', 'b'])
        assert args.my_unique_list == ['a', 'b']
    my_unique_list()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

argparse-best-practice-0.1.3.tar.gz (3.6 kB view details)

Uploaded Source

Built Distribution

argparse_best_practice-0.1.3-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file argparse-best-practice-0.1.3.tar.gz.

File metadata

  • Download URL: argparse-best-practice-0.1.3.tar.gz
  • Upload date:
  • Size: 3.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.9.2

File hashes

Hashes for argparse-best-practice-0.1.3.tar.gz
Algorithm Hash digest
SHA256 a32ddedcee8351d6cdbf71d0eb39d6c2dcc30633b63f683d71b8c1fe042b9e59
MD5 519874d4bb07204367a05e1c521cead1
BLAKE2b-256 1c7b1cd9290719247684495103c30817bc551a40bbff7986f413a24783298f2b

See more details on using hashes here.

File details

Details for the file argparse_best_practice-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: argparse_best_practice-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 6.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/53.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.9.2

File hashes

Hashes for argparse_best_practice-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 bdef2bf177081b7b6e3e666e320eee8b944b0dd2fbc7f68505e2c7706ed2b715
MD5 dc1e15418db410b91924105040ea7494
BLAKE2b-256 32fc0010cc01e74847ee557ba591150eac9bd026a577dbbd52ffbea17336ead1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page