Search code examples
pythonswitch-statementnonetype

Attempting to pass additional argument to a switcher library results in "'NoneType' object is not callable" error


I'm trying to pass two arguments to the switcher function, then use one of those arguments to define the switch case, and one of them to be passed to the case function. The portion of the code I provided has the function for one of the cases, the rest are similarly formatted.

I'm not sure if this is the right approach to creating this function, or why I am getting this error.

right = 1
def Default():
    print('Something went wrong :(')
def Right(duration):
    pyautogui.moveTo(1123,899) #Right Arrow Button
    pyautogui.mouseDown()
    time.sleep(duration)
    pyautogui.mouseUp()
    time.sleep(0.03)
def Move(direction,duration):
    switcher = {
        1: Right(duration) ,
        2: Left ,
        3: Down ,
        4: DiagonalUp 
        }
    return switcher.get(direction, Default)()
x = 2.5
Move(right,x)

The error I get is: line 48, in Move return switcher.get(direction, Default)() TypeError: 'NoneType' object is not callable

I do not get this error when I don't include the duration variable at all in the code.


Solution

  • Functions that don't return, implicitly return None. So this:

    def Default():
        print('Something went wrong :(')
    

    is the same as this:

    def Default():
        print('Something went wrong :(')
        return None
    

    Which means your dict get tries to do this:

    return switcher.get(direction, None)()
    

    Since there is no None key in switcher, it returns None and then None() is exectued... which is not valid since callable(None) = False

    You need Default to actually return a legitimate switcher key or raise an exception.