Skip to content

Format Code #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

Format Code #36

wants to merge 1 commit into from

Conversation

sayampradhan
Copy link

No description provided.

Copy link

@Sojka26 Sojka26 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import argparse

def get_args():
parser = argparse.ArgumentParser(description="Say hello")
parser.add_argument(
"-n", "--name", metavar="name", default="World", help="Name to greet"
)
return parser.parse_args()

def main():
args = get_args()
print("Hello, " + args.name + "!")

if name == "main":
main()

@nbehrnd
Copy link

nbehrnd commented Aug 6, 2025

The book recommends to assemble small functions, and to assemble their (inter)action within a separate function main. However, to assign this particular block the name main is unrelated to the "double underscore main" of

if __name__ == "__main__":
    main()

which indicates (perhaps even more so to a human reader, than to the Python interpreter) that the particular Python file is about a Python script for actual execution. Because, a Python file without the block of

if __name__ == "__main__":
    main()

) can serve as a collection of many functions (sort of numerical recipes) to be accessed and used only an import (think for instance of import math, or import re like) from the main file which happens to be the script.

See, save the following snippet as example.py -- despite a different name of the function which combines the other ones, it equally is functional.

#!/usr/bin/env python3
"""
name   :
author :
license:
date   :
edit   :
purpose: Rock the Casbah
"""

import argparse


def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='Rock the Casbah',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('positional',
                        metavar='str',
                        help='A positional argument')

    parser.add_argument('-a',
                        '--arg',
                        help='A named string argument',
                        metavar='str',
                        type=str,
                        default='')

    parser.add_argument('-i',
                        '--int',
                        help='A named integer argument',
                        metavar='int',
                        type=int,
                        default=0)

    parser.add_argument('-f',
                        '--file',
                        help='A readable file',
                        metavar='FILE',
                        type=argparse.FileType('rt'),
                        default=None)

    parser.add_argument('-o',
                        '--on',
                        help='A boolean flag',
                        action='store_true')

    return parser.parse_args()


def foo():
    """Join the functionalities"""

    args = get_args()
    str_arg = args.arg
    int_arg = args.int
    file_arg = args.file
    flag_arg = args.on
    pos_arg = args.positional

    print(f'str_arg = "{str_arg}"')
    print(f'int_arg = "{int_arg}"')
    print('file_arg = "{}"'.format(file_arg.name if file_arg else ''))
    print(f'flag_arg = "{flag_arg}"')
    print(f'positional = "{pos_arg}"')


# --------------------------------------------------
if __name__ == '__main__':
    foo()

@nbehrnd
Copy link

nbehrnd commented Aug 6, 2025

@sayampradhan The pairwise use of single/double quotes is a matter of style.*

There are code reformatters which can do this for you en bloc, for instance Black, or ruff. While consistency across a project and all of its Python files is a good thing, even better to ask all present contributors in advance about their preference before applying a style they consent to before installing this as a rule for instance as a pre-commit). Else run e.g., black -l 120 -S example_file.py to constrain the line length to 120 characters per line and to retain the pattern of single/double quotes (-S).

* Separate from using an apostrophe, the pairwise use of single and double quotes nested into each other can be helpful for a human reader, too.

@kyclark
Copy link
Owner

kyclark commented Aug 6, 2025

Thank you for your thoughtful comments. I (and many other Python programmers) use a "main" function because there is a long history in C-based languages of starting from "main." Because this repository is meant to hold the code that is presented in the book, I pretty much always reject PRs.

@kyclark kyclark closed this Aug 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants