0

I found some mysterious behavior that i simply cannot get to make sense, the "not" operator when applied to a false bool returns false. I am using Python 3.6 in a google cloud compute engine VM, running Ubuntu 18.04.

I have a main script and a second script where is store my some classes to be called from the main script. My main script looks like this:

import argparse
from second.script import MyClass
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--my_bool", default=False)
    args = parser.parse_args()
    myclass = MyClass()
    myclass.my_method(my_bool = args.my_bool)

my second script looks like this

class MyClass(MyParentClass):
    def my_other_method(self, some_other_inputs, my_bool=True,*args,**kwargs):
        if(something):
            print(my_bool, not my_bool)
            if(not my_bool):
                do_something

class MyParentClass():
    def my_method(self, some_other_inputs, *args,**kwargs):
        self.my_other_method(some_other_inputs, *args, **kwargs)

    def my_other_method(self, some_other_inputs, *args,**kwargs):
        raise NotImplementedError

now when the print statement happens it prints

False False

And the logic in the if statement underneath never executes. Like this the code looks a bit weird but i have tried to simplify it as much as possible to make it more readable. When i am calling the main script i am also parsing false to the my_bool argument, and i have checked that it is false when parsed to the myclass.my_method() Do any of you have a clue as to why this would happen?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    What is `type(my_bool)`? – Code-Apprentice Aug 04 '20 at 21:12
  • 1
    Ya, it actually being a string would be the most likely explanation. `print("False", not "False")` -> `False False`. – Carcigenicate Aug 04 '20 at 21:13
  • argparse returns the value of the flag as a string. So you are printing `"False"` and `not "False"` which both output `False`. – Code-Apprentice Aug 04 '20 at 21:15
  • I suggest using `action='store_true'` rather than `default=false`: https://docs.python.org/3/library/argparse.html#action – Code-Apprentice Aug 04 '20 at 21:18
  • 1
    Yes you guys are right, the args.my_bool was a string, i never considered that this could be the case since i never saw the interaction between not and string before. – user3453405 Aug 04 '20 at 21:39
  • @user3453405. Totally understandable. Keep in mind that `not` implicitly does `bool` first, so for summery you should print `bool(x), not x` unless you are sure that `type(x) is bool` already. – Mad Physicist Aug 04 '20 at 22:39

0 Answers0