Search code examples
pythonpython-3.xpyside2

None is False sometimes


I don't get why None default parameter prints two different things with same syntax.

class LoaderForm(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        print("Parent is: " + str(parent))
        self.button_Load.clicked.connect(self.load_project)

    def load_project(self, projectname=None):
        print("pojectname is: " + str(projectname))

>>> Parent is: None
>>> pojectname is: False

Why? I double-checked the code several times and I can't find the logic of it. It's worth to mention that I noticed this trying to use a condition for projectname inside load_project method:

        if projectname is None:
            #do something

Which of course doesn't works because projectname apparently is False for no reason.


Solution

  • A function is a first class object in Python. It can be passed to another function, just like any other object. This is exactly what is happening with self.button_Load.clicked.connect(self.load_project).

    So you need to look at what self.button_Load.clicked.connect is doing with your self.load_project method. Here, it is passing the argument False, which overrides the default None.

    Here's a minimal example to reproduce your issue:

    class MyClass():
        def __init__(self):
            self.connect(self.foo)
    
        def connect(self, func):
            func(False)
    
        def foo(self, var=None):
            print('Var is ' + str(var))
    
    A = MyClass()
    
    # Var is False