💾 Archived View for degrowther.smol.pub › 20240315_python_argv_main captured on 2024-07-09 at 00:27:34. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2024-03-21)
-=-=-=-=-=-=-
I’m not a Python programmer, but I’m writing a Python script for OFFLIRSOCH 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.