I read the documentation, but I still can't pinpoint exactly what it is this line of code is doing in compare. The code of compare is as follows:

#!/usr/bin/env python3

import argparse
import re
import sys

from helpers import lines, sentences, substrings

def main():

    # Parse command-line arguments
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--lines", action="store_true", help="compare lines")
    group.add_argument("--sentences", action="store_true", help="compare sentences")
    group.add_argument("--substrings", metavar="N", type=positive,
                       help="compare substrings of length N")
    parser.add_argument("FILE1", help="file to compare")
    parser.add_argument("FILE2", help="file to compare")
    args = vars(parser.parse_args())

    # Read files
        with open(args["FILE1"], "r") as file:
            file1 = file.read()
    except IOError:
        sys.exit(f"Could not read {args['FILE1']}")
        with open(args["FILE2"], "r") as file:
            file2 = file.read()
    except IOError:
        sys.exit(f"Could not read {args['FILE2']}")

    # Compare files
    if args["lines"]:
        matches = lines(file1, file2)
    elif args["sentences"]:
        matches = sentences(file1, file2)
    elif args["substrings"]:
        matches = substrings(file1, file2, args["substrings"])

    # Output matches, sorted from longest to shortest, with line endings escaped
    for match in sorted(matches, key=len, reverse=True):
        print(match.replace("\n", "\\n").replace("\r", "\\r"))

def positive(string):
    """Convert string to a positive integer."""
    value = int(string)
    if value <= 0:
        raise argparse.ArgumentTypeError("invalid length")
    return value

if __name__ == "__main__":

Specifically, what I don't understand is this paragraph about the implementation of compare:

Notice how the file defines a function called main and calls that function toward the bottom of the file. Defining main isn’t strictly necessary in Python, but it is necessary to define functions before you call them. Accordingly, because main calls a function called positive, and because we wanted to keep the "main" part of this program atop the file, it made sense to implement main as a function as well. That way, main doesn’t get called until the bottom of the file (after positive has been implemented), even though main is implemented atop the file.

Am I correct in thinking that the positive function will run first, and then the main function? But don't python scripts run top to bottom? So that main should run first and positive should run after?


You're right about Python scripts running top to bottom, but a function will be executed only after being called. In def positive(string) you're only defining a function, you're not calling it. In this script, the only function being called is main(), so only main will be executed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .