Skip to main content
3 of 6
added 97 characters in body
Graipher
  • 41.7k
  • 7
  • 70
  • 134

In addition to the comments from @vnp, which I agree with, consider simplifying your argparse to:

digests = { "md5": hashlib.md5, "sha1": hashlib.sha1, ... }

def _get_arguments(args=None):
    # Argument Parser for the overall function
    parser = argparse.ArgumentParser(
        description="Run hash sum functions on a file and return them.")
    parser.add_argument('-f', '--filepath',
                        help="Path to file to run sums on.", 
                        required=True)
    parser.add_argument('hashes',
                        nargs='*',
                        choices=digests,
                        default=['md5', 'sha1'],
                        help="Hashes to be used. Default: md5, sha1")
    return parser.parse_args(args)

The main difference now is that filepath now needs either the flag -f or --file in front of it. Alternatively it would have to come before the hashes, so it is possible to distinguish the possibly multiple hash arguments. The hashes don't take a - in front anymore either.

The choices of the hashes can use the dictionary of defined hashes @vnp recommended as well (No need for digests.keys() here, argparse does it correctly even when given a dictionary instead of a list).

I added the args parameter to allow testing of this function:

>>> _get_arguments(['-f', 'file'])
Namespace(filepath='file', hashes=['md5', 'sha1'])

>>> _get_arguments(['-f', 'file', 'md5'])
Namespace(filepath='file', hashes='md5')

>>> _get_arguments(['md5', '-f', 'file'])
Namespace(filepath='file', hashes=['md5'])

>>> _get_arguments(['-f', 'file', 'md5', 'sha256', 'sha512'])
Namespace(filepath='file', hashes=['md5', 'sha256', 'sha512'])
Graipher
  • 41.7k
  • 7
  • 70
  • 134