💾 Archived View for degrowther.smol.pub › 20240315_python_argv_main captured on 2024-08-18 at 18:20:17. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2024-03-21)

-=-=-=-=-=-=-

Python question: argv in main()?

I’m not a Python programmer, but I’m writing a Python script for OFFLIRSOCH 2024.

Announcing OFFLFIRSOCH 2024

Since I apparently refuse to use Stack Overflow, can somebody please let me know which of the following approaches is more idiomatic in Python?

Accessing sys.argv directly in main():

#!/usr/bin/env python3

import sys

def main() -> int:
    print(sys.argv)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Explicitly passing sys.argv to main():

#!/usr/bin/env python3

import sys
from typing import List

def main(argv: List[str]) -> int:
    print(argv)
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))

Making sys.argv the default value of an optional argument to main():

#!/usr/bin/env python3

import sys
from typing import Optional, List

def main(argv: Optional[List[str]] = None) -> int:
    if argv is None:
        argv = sys.argv
    print(argv)
    return 0

if __name__ == "__main__":
    sys.exit(main())

I’m using Python based on the assumption that most people who would use my script will already have it installed, and because the standard library is pretty deep. In other words, even though Python itself might be considered “bloated” by the standards of many small computing aficionados, I’m convinced that a single-file Python script is a good way to distribute a zero-dependency program of even moderate complexity.

Home