Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is setuptool's alternative to (the deprecated) distutils `strtobool`?

I am migrating to Python 3.12, and finally have to remove the last distutils dependency.

I am using from distutils.util import strtobool to enforce that command-line arguments via argparse are in fact bool, properly taking care of NaN vs. False vs. True, like so:

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-r", "--rebuild_all", type=lambda x: bool(strtobool(x)), default=True)

So this question is actually twofold:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • What would be an alternative to the deprecated strtobool?
  • Alternatively: What would be an even better solution to enforce ‘any string’ to be interpreted as bool, in a safe way (e.g., to parse args)?

>Solution :

What about using argparse’s BooleanOptionalAction? This is documented in the argparse docs, but not in a way that provides me with a useful link.

That would look like:

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-r", "--rebuild-all", action=argparse.BooleanOptionalAction, default=True)

And it would allow you to pass either --rebuild-all or --no-rebuild-all. This gets you an option that can be either true or false, but without the hassle of having to parse a string into a boolean value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading