Home > OS >  How to simplify two codes requiring the same tasks, but asking different parameter?
How to simplify two codes requiring the same tasks, but asking different parameter?

Time:09-22

I have a problem with simplifying my code.

I have two functions with the same job which is to close the window.

    def exit(self, event):
        self.running = False
        self.win.destroy()
        self.server.close()
        exit(0)

    def stop(self):
        self.running = False
        self.win.destroy()
        self.server.close()
        exit(0)

I separated them because the exit function requiring an event argument from here: self.win.bind_all("<Control-x>", self.exit)

And the stop function is used by this: self.win.protocol("WM_DELETE_WINDOW", self.stop)

This solution is redundant that is why I am thinking to simplify it by recycling one function. Is there any way that self.win.protocol("WM_DELETE_WINDOW", self.stop) will also use the exit function?

CodePudding user response:

Not sure what you are doing with the event object as your code snippet does not show it being used anywhere, however you can achieve your requirement by:

def exit(self, event=None):
    self.running = False
    self.win.destroy()
    self.server.close()
    exit(0)

event can be passed as an optional argument with default value as None if not passed, else the proper event object.
Here is a nice writeup on how to pass optional arguments to a function

CodePudding user response:

You could use a default argument. This would allow using the exit function in both cases.

def exit(self, event=None):
  • Related