Search code examples
pythonfunctioncallkill

Stop function from running twice


As a part of a program for an assessment piece, I have to include inventory management functions for network devices. Specifically - Add Devices, Remove Devices, Change Quantities, and List all Devices. Currently stuck on "Add Devices". When it runs, user is prompted to provide 3 inputs:

  1. Device key (e.g. "R" for Router - to be used later on so user can easily call object)
  2. Device name
  3. Quantity of device

These are stored in a dictionary array. In the function add_new_device(), I included an error check with an if statement - so if user were to enter an existing key or device name, they'd be prompted with a message, and then the function is called again to restart the add_new_device() function.

The Problem: Let's say use inputs "R" for device key (and it already exists). Message would prompt, and the function would restart. After then completing the inputs for key, name, and quantity, device name, and quantity from the previous call would finish executing.

How can I kill the current function call, and initiate a new instance of the function call?

def add_new_device():

    print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
    print("\n  > MAIN MENU > SHOW OR EDIT INVENTORY > ADD NEW DEVICE")

    new_device = {}

    print ("\nPlease enter a key for your device - e.g.  "R" for Router")
    new_devkey = input("\n\n Device key:  ")
    new_device["dev_key"] = new_devkey
    if any(x["dev_key"] == new_devkey for x in devices_all):
        print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
        print("\n               DEVICE KEY ALREADY EXISTS!")
        print("              PLEASE ASSIGN A DIFFERENT KEY")
        time.sleep(1)
        ### KILL CURRENT FUNCTION CALL HERE ###
        add_new_device()


    new_devname = input(" Device name:  ") 
    new_device["dev_name"] = new_devname
    if any(y["dev_name"] == new_devname for y in devices_all):

        print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
        print("\n              DEVICE NAME ALREADY EXISTS!")
        print("             PLEASE ASSIGN A DIFFERENT NAME")
        time.sleep(1)
        ### KILL CURRENT FUNCTION CALL HERE ###
        add_new_device()

        
    new_device["dev_quantity"] = input(" Device quantity:  ")

    devices_all.append(new_device)
    
    print("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
    print("\n              SUCCESSFULLY ADDED NEW DEVICE")
    print("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ")

    return new_device

Solution

  • You could do return add_new_device()

    instead of just: add_new_device()