fluentpython / example-code-2e

Example code for Fluent Python, 2nd edition (O'Reilly 2022)
https://amzn.to/3J48u2J
MIT License
3.26k stars 919 forks source link

ch21 cleanup, f-strings, and pathlib #4

Closed eumiro closed 3 years ago

eumiro commented 3 years ago

Some cleanup of the chapter 21, usage of f-strings, and pathlib.Path for dir/file operations. Alphabetic sorting of imports and some reformatting.

There's one point that is not the topic of this chapter, but the supplementary tests in argparse could be put directly into add_argument, but then the number of lines would explode:

    parser.add_argument(
        '-l', '--limit', metavar='N', type=int, help='limit to N first codes',
        default=sys.maxsize)
    …
    if args.limit < 1:
        print('*** Usage error: --limit N must be >= 1')
        parser.print_usage()
        sys.exit(1)

could be changed to:

    def validate_limit(value):
        try:
            res = int(val)
            if res < 1:
                raise ValueError()
        except ValueError:
            raise argparse.ArgumentTypeError("must be integer >= 1")
        else:
            return res
    parser.add_argument(
        '-l', '--limit', metavar='N', type=validate_limit, help='limit to N first codes',
        default=sys.maxsize)

But this was just to see how it works, so let's keep the argparse how it is.

ramalho commented 3 years ago

Thank you very much, @eumiro!