1

I ran my program using the below line

python ***.py --if_normalize False

but my program recognizes if_normalize variable to be True

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--work-path", required=True, type=str)
    parser.add_argument("--seed", default=42, type=int, help="Random seed")
    parser.add_argument("--batch-size", default=128, type=int)
    parser.add_argument("--attack", default='no', type=str)
    parser.add_argument("--gpu",default=2, type=int)
    parser.add_argument('--if_normalize', default=False, type=bool)
    return parser.parse_args()

args = parse_args()
print(args)

and it prints if_normalize is True

I passed 'False, false, -1' but still it recognizes as True

martineau
  • 119,623
  • 25
  • 170
  • 301
ylee
  • 111
  • 1
  • 1
  • 8
  • 1
    WIth `argparse` it's typical to use the parameter as "exists or not" rather than is True/False. So `parser.add_argument('--normalize', action='store_true')` is more appropriate. And it's either given as a parameter when running the script (`True`) or it's not given at all (`False`). Or in reverse with `action='store_false'`. If you really do want it as `--if_normalize True/False`, then [see the top 3 answers here](https://stackoverflow.com/q/15008758/1431750). – aneroid Feb 26 '21 at 08:36

3 Answers3

4

Because it just runs the input through bool, and bool('False') is True, because any non-empty string is truthy.

You'd usually do this by using a flag instead:

parser.add_argument('--if-normalize', action='store_true')

The store_true action implies a default of False, and sets it to True if the flag is present. I.e. you'd use it like:

$ python ***.py --if-normalize
deceze
  • 510,633
  • 85
  • 743
  • 889
1

You should change to the following:

parser.add_argument('--if_normalize', action='store_true')

This will set the argument if_normalize to True when you add it to the command line arguments when calling to your script.

You can refer to the docs and see exactly what it does.

David
  • 8,113
  • 2
  • 17
  • 36
1

https://docs.python.org/3/library/argparse.html#type

The bool() function is not recommended as a type converter. All it does is convert empty strings to False and non-empty strings to True. This is usually not what is desired.

This type section was recently expanded in an attempt to remove some common misunderstandings, including this misuse of the bool (a builtin) function.

You could write your own function that parses a whole slew of 'yes/no' words. Developers have declined to do so because there are too many alternatives, especially if non-English possibilities are included.

The store_true Action is enough for most purposes.

hpaulj
  • 221,503
  • 14
  • 230
  • 353